[wp-trac] [WordPress Trac] #63106: The loop can throw warning if `WP_Query::have_posts()` not called.
WordPress Trac
noreply at wordpress.org
Sat Mar 15 01:27:31 UTC 2025
#63106: The loop can throw warning if `WP_Query::have_posts()` not called.
---------------------------+-----------------------------
Reporter: peterwilsoncc | Owner: (none)
Type: defect (bug) | Status: new
Priority: low | Milestone: Awaiting Review
Component: Query | Version:
Severity: normal | Keywords:
Focuses: |
---------------------------+-----------------------------
Starting or overrunning the loop can throw a warning if
`WP_Query::have_posts()` is not called correctly via the developer. The
issue can be seen in these tests:
{{{#!php
<?php
function test_no_posts() {
$query = new WP_Query( array( 'post_type' => 'unregistered_cpt' )
);
$query->the_post();
$this->assertEmpty( $query->posts );
}
function test_too_many_calls() {
$post_id = $this->factory()->post->create();
$query = new WP_Query( array( 'p' => $post_id ) );
// Call the post twice.
$query->the_post();
$query->the_post();
$this->assertNotEmpty( $query->posts );
}
}}}
In each case the tests will throw an error before reaching the assertion,
as they are attempting to access an array key that does not exist.
A part of me is tempted to close this as wontfix, as it's very clearly
documented that one should use `while ( have_posts() )` for the primary
loop or `while $query->have_posts()` for a secondary loop.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/63106>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list