Extend the where clause in WordPress WP_Query
In WordPress, sometimes needing to modify WP_Query
class to interact with your database. For example, let's say you want to find all posts that the title would contain a specific keyword.
I guess your first attempt with WP_Query
would be this:
$my_query = new WP_Query(
array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 20,
'orderby' => array('menu_order' => 'ASC', 'date' => 'DESC'),
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
's' => $search_key
)
);
However, the above query searches the post content and title both. But we want it should search the post_title only.
I found out that WordPress offers a hook called posts_where
. Using this hook, we can extend the where clause of the WP_Query
. For that add the following lines in your functions.php
file:
add_filter( 'posts_where', 'extend_wp_query_where', 10, 2 );
function extend_wp_query_where( $where, $wp_query ) {
if ( $extend_where = $wp_query->get( 'extend_where' ) ) {
$where .= " AND " . $extend_where;
}
return $where;
}
This way you can use the
to customize your WP_Query.extend_where
$my_query = new WP_Query( array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 20,
'orderby' => array('menu_order' => 'ASC', 'date' => 'DESC'),
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'extend_where' => "(post_title like '%".$search_key."%' or post_title like '%".$search_key2."%')"
));
Please login or create new account to add your comment.