Wednesday 27 February 2019

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



from WC_Product_Query not working with have_posts()

No comments:

Post a Comment