Using wc_get_products function in WooCommerce

sarte picture sarte · Oct 24, 2017 · Viewed 8.2k times · Source

Bit puzzeled here.

add_action('plugins_loaded', 'foobar' );

function foobar(){
    $products = wc_get_products(array());
    var_dump($products);
}

This returns empty array. It doesn't seem to make difference what parameters I add to args. All I get is empty result.

What am I doing wrong?

Answer

LoicTheAztec picture LoicTheAztec · Oct 24, 2017

Updated

First plugin_loaded hook does not seems to be the right hook for this (but may be I am wrong)…

Now you need To add some minimal arguments to get your products:

$products = wc_get_products(array(
    'limit'  => -1, // All products
    'status' => 'publish', // Only published products
) );

To see the output in top of cart page (for example) to be sure you get something try just for testing purpose:

add_action('woocommerce_before_cart', 'custom_raw_output' );
function custom_raw_output(){
    $products = wc_get_products(array(
        'limit'  => -1,
        'status' => 'publish',
    ) );
    echo '<pre>'; print_r($products); echo '</pre>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works...