0

I have an archive page that lists a custom post type called 'event'. I have event posts with the tag 'regular', (the tag has an id of 53). I'd like to exclude these. I tried using pre_get_posts and then $query->set(('tag__not_in', array('53')) but I don't think tag__not_in will work with custom post types. Is there any way to fix this?

add_action( 'pre_get_posts', 'exclude_regular_tag');
function exclude_regular_tag( $query ){
    if ( is_admin() || ! $query->is_main_query() )
        return;
    if ( is_home() ) {
        return;
    }

    if ( is_post_type_archive( 'event' ) ) {
        $args = array('53'); //id of 'regular' tag in custom post type 'event'
        $query->set('tag__not_in', $args);
        return;
    }
}
  • you're using the built in post_tag taxonomy? tag__not_in is post type agnostic, it just creates a tax_query with the NOT IN operator. you can see it in source here. try having a look at the query in the template, var_dump( $wp_query ) and see if it's applying your tax parameters. – Milo Aug 13 '14 at 0:12
  • ["tag__not_in"]=> array(1) { [0]=> int(53) } This is in the query_vars array. I double checked the tag ID. It's definitely 53 but the post is still showing on the archive page. Any ideas? – Badex Aug 13 '14 at 9:43
  • ["tax_query"]=> object(WP_Tax_Query)#553 (2) { ["queries"]=> array(1) { [0]=> array(5) { ["taxonomy"]=> string(8) "post_tag" ["terms"]=> array(1) { [0]=> int(53) } ["include_children"]=> bool(true) ["field"]=> string(7) "term_id" ["operator"]=> string(6) "NOT IN" } } ["relation"]=> string(3) "AND" } – Badex Aug 13 '14 at 9:54
2

I used tax_query instead of tag__not_in and it works now.

if ( is_post_type_archive( 'event' ) ) {

      $taxquery = array(
        array(
            'taxonomy' => 'event-tag',
            'field' => 'id',
            'terms' => array( 53 ), //the ID of the event tag
            'operator'=> 'NOT IN'
        )
    );

    $query->set('tax_query', $taxquery);
    return;
}
  • It works because you are using a custom taxonomy, not the built in post tag taxonomy. tag__not_in only works for post_tag, not just any non-hierarchical taxonomy. – Milo Aug 13 '14 at 14: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.