// How to increase the limit of the customer when he purchases some product in WooCommerce (settings are in the 'Posts Limit' tab of the product edit screen)? (based on Posts limit per user add-on)
add_filter( 'woocommerce_product_data_tabs', 'upl_wc_product_tab' );
add_action( 'woocommerce_product_data_panels', 'upl_wc_product_panel' );
add_action( 'woocommerce_process_product_meta_simple', 'upl_wc_save_product_options' );
add_action( 'woocommerce_order_status_processing', 'upl_wc_update_user_limit', 10, 2 );

function upl_wc_product_tab( $tabs ) {
	$tabs['posts_limit'] = [
		'label'		=> __( 'Posts Limit', 'user-posts-limit' ),
		'class'		=> [ 'show_if_simple' ],
		'target'	=> 'posts_limit_product_data',
	];
	return $tabs;
}

function upl_wc_product_panel() {
	echo '<div id="posts_limit_product_data" class="panel woocommerce_options_panel hidden">';
	woocommerce_wp_text_input( [
		'id'		=> '_num_limit',
		'label'		=> __( 'Posts Grant', 'user-posts-limit' ),
		'description'	=> __( 'It defines the the amount of posts the product grant', 'user-posts-limit' ),
		'desc_tip'		=> true,
		'type'		=> 'number',
		'custom_attributes' => [ 'step' => 'any', 'min' => '0' ],
	] );
	echo '</div>';
}

function upl_wc_save_product_options( $product ){
	update_post_meta( $product, '_num_limit', isset( $_POST['_num_limit'] ) && 0 < $_POST['_num_limit'] ? floatval( $_POST['_num_limit'] ) : null );
}

function upl_wc_update_user_limit( $order_id, $order ) {
	$user_id = $order->get_user_id();
	foreach ( $order->get_items() as $item ) {
		$product = $item->get_product();
		if ( $product && '' === $item->get_meta( '_num_limit_applied' ) ) {
			$product_posts = $product->get_meta( '_num_limit' );
			if ( $product_posts ) {
				$current_limit = get_user_meta( $user_id, 'num_limit', true );
				$increase = $item->get_quantity() * $product_posts;
				update_user_meta( $user_id, 'num_limit', $current_limit ? $current_limit + $increase : $increase );
				$item->add_meta_data( '_num_limit_applied', $increase, true );
				$item->save();
			}
		}
	}
}