Skip to main content

Custom WP_Query SQL WHERE Clause using posts_where : WordPress Code Snippet

There may be times when you need to add to the WHERE clause within a WP_Query call for additional SQL filtering that cannot easily be achieved via the standard parameters.

The following is a simple example that passes through a search term value and adds a LIKE comparison on the post title.

Add the following to your functions.php file:

function search_title_filter( $where, &$wp_query ) {
    global $wpdb;

    if ( $search_term = $wp_query->get('keyword_search') ) {
        $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $search_term ) ) . '%\'';
    }

    return $where;
}

Make use of this within the area of code that you are making the query:

$search_term = 'ABC';

$args = [
    'post_type'      => 'custom_post_type',
    'posts_per_page' => -1,
    'keyword_search' => $searchTerm,
];

add_filter( 'posts_where', 'search_title_filter', 10, 2 );
$the_query = new WP_Query( $args );
remove_filter( 'posts_where', 'search_title_filter', 10, 2 );

The array key ‘keyword_search‘ can be changed as required – it is simply referred to in the check within the search_title_filter function.