1

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',
            array(
                'key' => 'my_field',
                'value' => $search_word,
                'compare' => 'IN'
            ),
            array(
                'key' => 'post_title',
                'value' => $search_word,
                'compare' => 'IN',
            )
        )
    );

    //$query = new WP_Query( $args ); //Need to modify the existing WP_Query
    $query->init();
    $query->parse_query($args);
}

}
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.

0

To do an OR search, I tried merging WP_Query results as shown here - Can i merge 2 new WP_Query($variable) 's? - in guidod's answer. That wasn't a great solution though, and resulted in erratic behaviour.

The correct solution I found was to modify the query using the WP Custom Query as shown in the code (which requires some modifications) here - http://codex.wordpress.org/Custom_Queries ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.