I am trying to loop through my WooCommerce products like you would with Custom Post Types. But for some reason this method isn't working. I am getting an error which is to do with me using have_posts()
. What am I doing wrong?
Error
Uncaught Error: Call to a member function have_posts() on array
My code
<?php
$query = new WC_Product_Query( array(
'limit' => 10,
'orderby' => 'date',
'order' => 'DESC'
) );
$products = $query->get_products();
if( $products->have_posts() ) {
while( $products->have_posts() ) {
$products->the_post();
echo the_permalink();
}
} ?>
Update
I have found that using a foreach loop does work like the following;
<?php
foreach( $products as $product ) {
echo $product->get_title();
} ?>
But I'd still like to understand why this method doesn't work with have_posts()
$query = new WC_Product_Query(array(
'limit' => 10,
'orderby' => 'date',
'order' => 'DESC'
));
$products = $query->get_products();
if (!empty($products)) {
foreach ($products as $product) {
echo get_permalink($product->get_id());
}
}
function have_post()
is member function of WordPress WP_Query
class - and WooCommerce WC_Product_Query
class is extending WC_Object_Query
class, not the WP_Query
- So this function cannot be called
Because $products is array, so you can't call a method in it, just at some item. If you did $products[0]->have_posts() it would work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With