How to create/modfiy WP_Query to search in post title OR custom field?


I need to modify or create a WP_Query that will search for a search term in both the post title OR a custom field (called ‘my_field’).

I have been reading and trying for hours, but I am right back to this code (below) which, alas, only searches in ‘my_field’ and does not take the post_title into account.

function my_pre_get_posts_2( $query ) {
if ( is_admin() && $query->is_main_query() && $query->query['post_type'] === 'post' && isset($query->query['s']) ) {

    $search_word = $query->query['s'];

    $args = array(
        //'s' => $search_word, //If I include this line, the WP query seems to AND post_title and my_field. If I comment out this line, the WP query only searches in my_field
        'post_type' => 'post',
        'meta_query' => array(
            'relation' => 'OR',
                'key' => 'my_field',
                'value' => $search_word,
                'compare' => 'IN'
                'key' => 'post_title',
                'value' => $search_word,
                'compare' => 'IN',

    //$query = new WP_Query( $args ); //Need to modify the existing WP_Query

add_action( 'pre_get_posts', 'my_pre_get_posts_2' );

The reason I need to do this is because I need to modify the behaviour of the the ‘Search Posts’ button in the ‘All Posts’ (admin) page so that whatever the admin user searches for, it will return the posts that have a matching post title OR my_field value.

, ban-geoengineering 4 years 2020-06-02T09:10:24-05:00 0 Answers 100 views 0

Leave an answer