Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using wc_get_products function in WooCommerce

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?

like image 208
sarte Avatar asked Oct 24 '17 05:10

sarte


1 Answers

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...

like image 193
LoicTheAztec Avatar answered Sep 28 '22 23:09

LoicTheAztec