简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM