Question

I have got a product loop to display 8 products on my homepage. It is simply a loop which starts from the end of the product list to the beginning and displays all of my products until it reaches the 8th one. When I put a conditional statement that I want only products with certain titles displayed it does select only those, but only from the list of products which would be displayed without the conditional statement.

For example consider such a list of ALL products in the shop:

[beginning of the list] 'Globus 1' 'Globus 2' [... some more products ...] 'Kompozycja 6' 'Kompozycja 7' [end of the list]

My loop grabs items from the last item to the first one and limits the amount of products displayed to 8. I've put a conditional statement that I want only 'Kompozycja 7' to be displayed and it worked. But if I specify a name which is not one of the last 8 items on the list then it will not work. For example I will choose 'Globus 1'. It won't be displayed because it does not belong to the last 8 items on the list.

Here is my loop:

$args = array(
    'post_type' => 'product',
    'posts_per_page' => 8
    );
$loop = new WP_Query( $args );

if ( $loop->have_posts() ) {
        while ( $loop->have_posts() ) : $loop->the_post();
        if (get_the_title($post->ID) == 'Kompozycja 7' || get_the_title($post->ID) == 'Kompozycja 2') {
                woocommerce_get_template_part( 'content', 'product' );
        }   
        endwhile;
    } else {
        echo __( 'No products found' );
    }

Could anybody help me with that?

Was it helpful?

Solution

Your problem is that you limit the number of posts before your conditional loop. The line $loop = new WP_Query( $args ); returns a max of 8 results for your loop to iterate.

You could return the whole set of results and limit it yourself with a counter:

$args = array(
    'post_type' => 'product',
    'posts_per_page' => -1 //return all posts
);
$loop = new WP_Query( $args );
//create a counter
$count=0;

if ( $loop->have_posts() ) {
    //loop whilst we have posts and we still require more
    while ( $loop->have_posts() && $count < 8 ) : $loop->the_post();
        if (get_the_title($post->ID) == 'Kompozycja 7' || get_the_title($post->ID) == 'Kompozycja 2') {
            woocommerce_get_template_part( 'content', 'product' );
            //increment count - if it reaches 8 we quit the loop
            $count++;
        }
    endwhile;
} else {
    echo __( 'No products found' );
}

Although if you have many thousands of products this will be slow. There is propably an argument you can pass to WP_Query instead to perform this check at the database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top