0

I wanted to test how many times a while would loop through a query array.

$WatchListArgs = array(
    'post_type'     => 'post',
    'post_status'   => 'publish',
    'category__and' => array( 4, 16 ),
);

$WatchListQuery = new WP_Query( $WatchListArgs ); 
$WatchListCount = $WatchListQuery->found_posts;
if ( $WatchListCount > 0 ) {
    echo '<h2>Watch List</h2>';

    if ( have_posts() ) {
        echo 'There are ' . $WatchListCount . ' Watch List posts';

        while ( have_posts() ) :
            the_post();
            echo '*';
        endwhile;
    }
} // end if 

The result was There are 1 Watch List posts************

Why are there 12 asterisks, instead of 1?

Note: I already understand that many developers don't like echo.

2
  • I'm not sure why my ''' for code isn't working correctly. Jul 13, 2023 at 16:57
  • 1
    Need to use backticks (`), rather than single quotes.
    – Caleb
    Jul 13, 2023 at 17:04

1 Answer 1

2

This is because have_posts() is for the main loop, and not your custom query. Prefixing each use of have_posts() and the_post() with $WatchListQuery-> will fix it:

if ( $WatchListQuery->have_posts() ) {
while ( $WatchListQuery->have_posts() :
    $WatchListQuery->the_post();
2
  • This query is actually preceded by another query for Upcoming Conferences. I thought that a custom query object replaced the main loop. I think that is where the error in my thinking came in. These two query objects do not replace the main loop, the main loop is still there, it's just not used! Jul 14, 2023 at 3:45
  • Magic! Not only did it fix the problem, it taught me something new about scope in the WordPress query object. Jul 14, 2023 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.