Using WordPress ‘posts_search’ PHP filter

The posts_search filter modifies the search SQL used in the WHERE clause of a WordPress WP_Query.

Usage

add_filter('posts_search', 'your_function_name', 10, 2);
function your_function_name($search, $query) {
    // your custom code here
    return $search;
}

Parameters

  • $search (string) – The search SQL for the WHERE clause.
  • $query (WP_Query) – The current WP_Query object.

More information

See WordPress Developer Resources: posts_search

Examples

Change search logic

Modify the search logic to include searching for post tags.

add_filter('posts_search', 'search_tags_in_posts', 10, 2);
function search_tags_in_posts($search, $query) {
    if (!is_admin() && $query->is_search) {
        global $wpdb;
        $search_term = esc_sql($query->query['s']);
        $search .= " OR (t.name LIKE '%{$search_term}%')";
        $search = " AND ({$search}) ";
    }
    return $search;
}

Exclude specific post types from search

Prevent search from returning results for specific post types.

add_filter('posts_search', 'exclude_post_types_from_search', 10, 2);
function exclude_post_types_from_search($search, $query) {
    global $wpdb;
    if (!is_admin() && $query->is_search) {
        $search .= " AND {$wpdb->posts}.post_type NOT IN ('exclude_this_post_type', 'exclude_this_too')";
    }
    return $search;
}

Extend the search to include custom fields (meta values).

add_filter('posts_search', 'include_custom_fields_in_search', 10, 2);
function include_custom_fields_in_search($search, $query) {
    global $wpdb;
    if (!is_admin() && $query->is_search) {
        $search_term = esc_sql($query->query['s']);
        $search .= " OR ({$wpdb->postmeta}.meta_value LIKE '%{$search_term}%')";
    }
    return $search;
}

Filter search results by category

Limit search results to a specific category.

add_filter('posts_search', 'filter_search_by_category', 10, 2);
function filter_search_by_category($search, $query) {
    if (!is_admin() && $query->is_search) {
        $search .= " AND ({$wpdb->term_taxonomy}.taxonomy = 'category' AND {$wpdb->term_taxonomy}.term_id = 'your_category_id')";
    }
    return $search;
}

Prevent search results from returning posts containing specific words.

add_filter('posts_search', 'exclude_words_from_search', 10, 2);
function exclude_words_from_search($search, $query) {
    global $wpdb;
    if (!is_admin() && $query->is_search) {
        $search .= " AND {$wpdb->posts}.post_content NOT REGEXP '(word1|word2|word3)'";
    }
    return $search;
}