Support

Account

Home Forums General Issues Custom field search

Solved

Custom field search

  • Hi! I am trying to implement a rather simple (by the looks) thing: change the default WP search query to also search not only in the title and content, but in my custom field. After doing quite some searching I compiled this function that I add to my functions.php file.

    function search_filter($query) {
    	if ( !is_admin() && $query->is_main_query() ) {
    		if ($query->is_search) {
    
    			$meta_query = array(
    				'relation'		=> 'OR',
    				'adresas_clause' => array(
    					'key'       => 'adresas',
    					'value'     => $query->query['s'],
    					'compare'	=> 'LIKE'
    				)
    			);
    
    			// $query->set('post_type', 'post');
    			$query->set('meta_query', $meta_query);
    		}
    	}
    	return $query;
    }
    
    add_action('pre_get_posts','search_filter');

    But it does not really work. If I search for the post that both title and custom field “adresas” match – I get the results. But if one of them does not match, I get nothing. Though the relation is set to “OR”, so either title or custom field should be matched. What am I missing?

    Also tried using “AND” (then search completely stops working) and different “compare” options. Nothing worked.

    I hope you could help me with this.

  • You can’t do this with just a meta_query, it’s more involved. You also need to modify WHERE portion of the query to change it from AND to OR. There is a decent explanation of this here http://adambalee.com/search-wordpress-by-custom-fields-without-a-plugin/

  • Thank you! With some changes to search only in specific field and changing query to only search for posts, it works now as it should.

  • If someone is looking for a solution to this problem is to recommend the plugin:
    https://wordpress.org/plugins/acf-better-search/

    This plugin adds to default WordPress search engine the ability to search by content from selected fields of Advanced Custom Fields plugin.

    Everything works automatically, no need to add any additional code.

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Custom field search’ is closed to new replies.