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)?

1 Answer
1

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.

Leave a Reply

Your email address will not be published. Required fields are marked *