Reputation: 55
In Woocommerce I am trying to get all products using wc_get_products()
as follow:
$args = array( 'status' => 'publish' );
$products = wc_get_products( $args );
return $products;
But it return an empty string.
How can I get all products using wc_get_products()
? What I am doing wrong?
Upvotes: 3
Views: 12566
Reputation: 176
My problem was that
wc_get_products($args);
wasn't initialized. You need to check that case first. It might be that you add_action hook is having an inappropriate priority. Make sure that woocommerce initialized first before calling that funciton.
Upvotes: 1
Reputation: 253784
Your code works and will give you an array of the 10 last created WC_Product
objects. So when you return this array of WC_Product objects, it gives nothing as it's not a string.
If you want to get all products you need to add 'limit'
argument with a value of -1
like:
// An array of all published WC_Product Objects
$products = wc_get_products( array( 'status' => 'publish', 'limit' => -1 ) );
// Displaying the number of products in this array
echo '<p>Number of products: ' . sizeof( $products ) . '</p>';
// Loop through products and display some data using WC_Product methods
foreach ( $products as $product ){
echo '<p>';
echo 'Type: ' . $product->get_type() . '<br>'; // Product type
echo 'ID: ' . $product->get_id() . '<br>'; // Product ID
echo 'Title: ' . $product->get_title() . '<br>'; // Product title
echo 'Price: ' . $product->get_price(); // Product price
echo '</p>';
}
Example - The following code will output in a string a coma separated suite of all your product IDs:
echo '<p>Products IDs list: ' . implode( ', ', wc_get_products( array( 'status' => 'publish', 'limit' => -1, 'return' => 'ids' ) ) ) . '</p>';
Tested and works.
Upvotes: 13