• New to WC. I see that variations are stored in the wp_posts table as an additional post with the post parent set to, well, the “Product Post” that created them. Makes sense. My Question is how do I retrieve these efficiently? For instance:

    <?php
           // Get
    	$args = array(
    		'post_type' => 'product',
    		'posts_per_page' => 3,
    		'category' => 'care',
    		'order' => 'ASC'
    	);
    	$plans = get_posts( $args );
    
    	foreach($plans as $plan):
    
    		$args = array(
    			'post_parent' => $plan->ID,
    			'post_type'   => 'product_variation',
    			'numberposts' => -1,
    			'post_status' => 'any'
    		); 
    
    		$variations = get_posts( $args );
    
    		// Do stuff with product variation data
    
    	endforeach;
    
     ?>

    The above works. However, there must be a better way?

    https://wordpress.org/plugins/woocommerce/

Viewing 4 replies - 1 through 4 (of 4 total)
  • Plugin Contributor royho

    (@royho)

    Use the product class method get_available_variations().

    Thread Starter justinwhall

    (@jwind)

    So:

    $variations = $product->get_available_variations();

    In my case, $product is not a global variable. I don’t see how I’d use get_available_variations() within my loop.

    Plugin Contributor royho

    (@royho)

    So from your code, you would say:

    $plan = wc_get_product( $plan->ID );
    
    $variations = $plan->get_available_variations();
    Thread Starter justinwhall

    (@jwind)

    Aha. Figured it was simple. Many thanks.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Get product variations in product loop’ is closed to new replies.