WordPress.org

Ready to get started?Download WordPress

Forums

Exclude post_title and post_content from search query (1 post)

  1. danromanchik
    Member
    Posted 4 months ago #

    I have added a function to functions.php to search the meta fields of some custom posts:

    function custom_search_query( $query ) {
    	if ( !is_admin() && $query->is_search ) {
    		$meta_query_args = array(
    			'relation' => 'OR',
    			array(
    				'key' => 'key1',
    				'value' => $query->query_vars['s'],
    				'compare' => 'LIKE',
    			),
    			array(
    				'key' => 'key2',
    				'value' => $query->query_vars['s'],
    				'compare' => 'LIKE',
    			),
    		);
    		$query->set('meta_query', $meta_query_args);
    	};
    }
    add_filter( 'pre_get_posts', 'custom_search_query');

    This does add search terms to query as shown below:

    AND ( (wp_postmeta.meta_key = 'key1' AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%string%') OR (mt1.meta_key = 'key2' AND CAST(mt1.meta_value AS CHAR) LIKE '%universe%') )

    But this still isn't doing what I want it to do. If the search string isn't in the post_title, I don't get any search results. So, what I need to do is somehow eliminate the post_title from the search or change the first AND in the clause above to OR. Any ideas on how to do this?

Reply

You must log in to post.

About this Topic