1

How do I get all posts that has a taxonomy term and a specific name/slug?

I have tried with the following arguments but without getting the wanted result. What am I missing, how can I combine the slug and term in the same query?

array(      
    'name' => '<name of post>',
    'tax_query' => array(
        array(
            'taxonomy' => '<taxonomy>',
            'field' => 'slug',
            'terms' => <slug>,
            'operator' => 'IN'
        )
    ),      
)

The SQL:

SELECT  wp_posts.* FROM wp_posts  WHERE 1=1  AND wp_posts.post_name = '<slug-name>' AND wp_posts.post_type = '<post type>' AND ((wp_posts.post_status = 'publish'))  ORDER BY wp_posts.post_date DESC

If I remove the "name" field the taxonomy part of the SQL looks right.

array(
    'tax_query' => array(
        array(
            'taxonomy' => '<taxonomy>',
            'field' => 'slug',
            'terms' => <slug>,
            'operator' => 'IN'
        )
    ),      
)

The SQL:

SELECT   wp_posts.* FROM wp_posts  INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1  AND ( 
  wp_term_relationships.term_taxonomy_id IN (2)
) AND wp_posts.post_type = '<post type>' AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 5"
1

Note that if you have the post slug, you don't need the additional taxonomy query to find that post, so it makes sense to drop the expensive taxonomy query in core in that case.

Otherwise you could try instead the post_name__in parameter:

[      
    'post_name__in' => [ '<postslug>' ],
    'tax_query' => [
        [
            'taxonomy' => '<taxonomy>',
            'field' => 'slug',
            'terms' => <slug>,
            'operator' => 'IN'
        ]
    ],      
];

that was introduced in WordPress 4.4, if you really want the taxonomy query part included as well ;-)

  • I came to that conclusion as well. Thanks for your reply. – user634545 Jan 21 '16 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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