Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WC_Product_Query not working with have_posts()

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()

like image 378
Reece Avatar asked Feb 24 '19 16:02

Reece


2 Answers

$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

like image 76
mujuonly Avatar answered Nov 09 '22 03:11

mujuonly


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.

like image 1
Marco Avatar answered Nov 09 '22 02:11

Marco