WordPress Snippets at WPcustoms

Bad word filter for search queries

posts_where jumps into the query and modifies it similar to pre_get_posts. We limit it to search queries with the conditional tag is_search and forward the WHERE argument to exclude post titles containing “bad word”. This example can be adapted to various tasks i.e. only include posts in the search results containing a specific value in a custom meta field.


/**
 * Snippet Name: Bad word filter for search queries
 * Snippet URL: https://wpcustoms.net/snippets/bad-word-filter-search-queries/
 */
  function wpc_badword_search_filter ($where){
    if (is_search ()) {
        global $wpdb;
        $where .= " AND $wpdb->posts.post_title NOT REGEXP '^.*bad word.*$'";
    }
    return $where;
}
add_filter('posts_where', 'wpc_badword_search_filter' );