• Hi all, thought I’de share some code.

    I needed to exclude posts marked as ‘expired’ from showing up. The posts are under the custom post type of ‘article’ And I’ve created the term ‘expired’ which sits under the taxonomy ‘things-to-do’. Having researched this in the codex I decided to create a function in functions.php to exclude the category by hooking into pre_get_posts.

    The code I’ve used is below. Hopefully it could be of use to others and of course I’d be interested to learn if this is the best way to o it:

    function exclude_category( $query ) {
        if ( $query->is_tax() && $query->is_main_query() ) {
    
            $args = array(
                'post_type' => 'article',
                'tax_query' => array(
                    array(
                        'taxonomy' => 'things-to-do',
                        'field'    => 'slug',
                        'terms'    => array( 'expired' ),
                        'operator' => 'NOT IN',
                    )
                ),
            );
    
            $query->set( 'tax_query', $args);
    
        }
    }
    add_action( 'pre_get_posts', 'exclude_category' );
  • The topic ‘Exclude custom post types and taxonomies from the query’ is closed to new replies.