Exclude posts from search by taxonomy ids

A nifty function to exclude posts which contain specified term ids. Now thats one hell of a sql query… It’s also possible to use this with a custom taxonomy – just replace post_tag with your taxonomy name. Feel free to change the conditional tag is_search to use this on any other query.

 * Snippet Name: Exclude posts from search by taxonomy ids
 * Snippet URL: https://www.wpcustoms.net/snippets/exclude-posts-from-search-by-taxonomy-ids/
  function wpc_manipulate_post_where ($where){
    if (is_search()) {
        global $wpdb;
        //exclude posts which contains tag id=10,13,2
        $filter =  " AND tt.term_id IN ('10', '13', '2')";
        $where .= " AND $wpdb->posts.ID NOT IN ";
        $where .= "(SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy = 'post_tag'".$filter.")";
    return $where;
add_filter('posts_where', 'wpc_manipulate_post_where' );

0 0 vote
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x