2
votes

I have a WooCommerce shop that holds variable products.

I want to create some sort of export (on a page) that shows me all products including variations in a table.

I am viewing all products and created a loop to get the variations but it only shows me one product variation.

<?php
/*
Template Name: Store Management
*/
if (!is_user_logged_in() || !current_user_can('manage_options')) wp_die('This page is private.');
// Get
$args = array(
    'post_type' => 'product',
    'numberposts' => -1,
);
$products = get_posts( $args );
echo '<pre>';
print_r($products);
echo '</pre>';

foreach($products as $product):

    $args = array(
        'post_parent' => $plan->ID,
        'post_type'   => 'product_variation',
        'numberposts' => -1,
    ); 

    $product = wc_get_product( $product->ID );

    $variations = $product->get_available_variations();
    echo '<pre>';
    print_r($variations);
    echo '</pre>';

endforeach;

?>

Can anyone tell me how to get all variations for all products?

M.

2

2 Answers

5
votes

Here is my code, to get all products and variations in WooCommerce v3+ :

<?php
$args = [
    'status'    => 'publish',
    'orderby' => 'name',
    'order'   => 'ASC',
    'limit' => -1,
];
$all_products = wc_get_products($args);
foreach ($all_products as $key => $product) {
    echo $product->get_title();
    if ($product->get_type() == "variable") {
        foreach ($product->get_variation_attributes() as $variations) {
            foreach ($variations as $variation) {
                echo $product->get_title() . " - " . $variation;
            }
        }
    }
}
2
votes

First of all don't override the product variable inside loop. Secondly you have to check weather product is simple or variable. Because simple product will not have variants. So your code will be like this :

foreach($products as $product):
$product_s = wc_get_product( $product->ID );
if ($product_s->product_type == 'variable') {
    $args = array(
        'post_parent' => $plan->ID,
        'post_type'   => 'product_variation',
        'numberposts' => -1,
    );
    $variations = $product_s->get_available_variations();
    echo '<pre>';
    print_r($variations);
    echo '</pre>';
}
endforeach;