2

I've got a wordpress site with several custom post types. On a page, I want to display only posts of a custom type that have a specific tag. I've been using the following query to do so:

$args = array(
    'tag_slug__in'    => array('tag1', 'tag2'),
    'post_type'       => 'custom_post',
    'post_status'     => 'publish',
    'posts_per_page'  => 10,
    'order'           => 'ASC',
    'orderby'         => 'menu_order'
);

$posts = new WP_Query( $args );

However, when I run this query, I get both the page I have tagged like this, and a different custom post type (event) with the tags. However, I should have this limited to the stated custom_post type. I've double checked that the name I provided matches the name of the custom post type.

Obviously, I could trivially filter this myself at the start of the loop to only display my custom post type, but I want to properly handle returning no results. Is there a way to have the query properly filter my results to JUST posts with both this custom type and the listed tag(s)?

3
  • 1
    What is echo $posts->request; ?
    – birgire
    Commented Apr 19, 2018 at 8:24
  • Weird, I just pulled that and got this: SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (16) ) AND wp_posts.post_type IN ('post', 'page', 'attachment', 'event', 'custom_post', 'custom_post2') AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order ASC LIMIT 0, 10 Why would it be suddenly changing my filtered post types to all post types?
    – neomang
    Commented Apr 19, 2018 at 14:36
  • 1
    Could be a plugin/theme that is changing the query.
    – birgire
    Commented Apr 19, 2018 at 18:21

1 Answer 1

5

Since tag is a taxonomy of a custom_post post type, the query could look like this:

<?php
$args = array(
    'post_type'  => 'custom_post',
    'tax_query'  => array(
        array(
            'taxonomy'  => 'post_tag',
            'field'     => 'slug',
            'terms'     =>  array(
                'tag1',
                'tag2',
            ),
        ),
    ),
);

$posts = new WP_Query( $args );

See WP_Query Taxonomy Parameters.

2
  • This is wrong. A tag is not with tax_query. It should be possible with "tag_slug__in". If not you have done something wrong ....
    – yfain
    Commented Jul 29, 2021 at 20:45
  • Built-in WordPress tags are not associated with custom post types by default and are assigned to regular posts only. The question was about a specially registered taxonomy for the custom post type.
    – Max Yudin
    Commented Jul 31, 2021 at 6:54

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.