Make WordPress Core

Opened 8 years ago

Closed 8 years ago

Last modified 8 years ago

#36381 closed defect (bug) (invalid)

query_posts neglecting other parameters when 'name' is used

Reported by: ioweuiraosjfosj's profile ioweuiraosjfosj Owned by:
Milestone: Priority: normal
Severity: trivial Version: 4.4.2
Component: Query Keywords:
Focuses: Cc:


When using the query_posts with the 'name' parameter it will always return the post even if the given post does not match with the other parameters.

This will return the post 'Hello World' even though its NOT in the category.

query_posts( array ( 'category_name' => 'category', 'name' => 'hello-world' ) );
while (have_posts()):
    get_template_part( 'content', get_post_format() );

This is a workaround that works:

query_posts( array ( 'name' => 'hello-world' ) );
while (have_posts()):
    if( in_category('category') ) get_template_part( 'content', get_post_format() );

Change History (2)

#1 follow-up: @boonebgorges
8 years ago

  • Milestone Awaiting Review deleted
  • Resolution set to invalid
  • Status changed from new to closed

Hi @ioweuiraosjfosj - Thanks for the report.

The behavior you've described is by design. Providing the 'name' parameter to WP_Query overrides other parameters, and performs a single-post query for an item where post_name = $name.

If you need a non-exclusive way to narrow down posts by post_name, try post_name__in:

$q = new WP_Query( array(
    'post_name__in' => 'hello-world',
    'category_name' => 'category',
) );
while ( $q->have_posts() ) :
    // ...

Side note: it's almost always incorrect to use query_posts() in a theme or plugin. Create a new WP_Query object as shown above.

#2 in reply to: ↑ 1 @ioweuiraosjfosj
8 years ago

  • Severity changed from normal to trivial

Thank you!
I was afraid you'd say that. Maybe we could update this information in here:
There is no mentioning of the override of the 'name' parameter.

Note: See TracTickets for help on using tickets.