Make WordPress Core

Opened 9 years ago

Closed 9 years ago

Last modified 9 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:

Description

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()):
    the_post();
    get_template_part( 'content', get_post_format() );
endwhile;

This is a workaround that works:

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

Change History (2)

#1 follow-up: @boonebgorges
9 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() ) :
    $q->the_post();
    // ...
endwhile;

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. https://codex.wordpress.org/Function_Reference/query_posts

#2 in reply to: ↑ 1 @ioweuiraosjfosj
9 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: https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters
There is no mentioning of the override of the 'name' parameter.

Note: See TracTickets for help on using tickets.