Search code examples
phpwordpresswoocommerceproduct-variations

WooCommerce adding product variations programatically with different price will not reflect on the product page


Let me put it simple.

  1. We have products with color and size attributes in database
  2. The products are all variable products
  3. Variations are added for every color and "Any" size

Then we wrote a few functions to add 2 more variations to each product for the sizes 2XL and 3XL (the products are t-shirts) with a higher price!

The variations are added beautifully, however, on the front end, the price will not change when I select the size with the increased price unless I go to a product edit page and click the update button. Only then will the price to be added to the cart change upon selecting that size.

How can make the variations with the increased price reflect on the front-end without having to click the update button for each product?


Solution

  • Maybe you need to run variable_product_sync() on each variable product?

    function so_run_once(){
    
        $variable_products = get_posts( array(
                'posts_per_page'=> -1,
                'post_type'     => 'product',
                'fields'        => 'ids',
                'post_status'   => 'publish',
                'tax_query' => array(
                array(
                    'taxonomy' => 'product_type',
                    'field'    => 'slug',
                    'terms'    => 'variable',
                ),
            )
        ) );
    
        if( $variable_products ) foreach( $variable_products as $product_id ){
            $_product = wc_get_product( $product_id );
            $_product->variable_product_sync();
        }
    }
    add_action( 'admin_init', 'so_run_once' );