This website uses cookies to personalize your experience. By using this website you agree to our cookie policy.

Reply To: Search only in custom field

#32209
Ernest MarcinkoErnest Marcinko
Keymaster

Sure!

There is the asp_query_args hook, which lets you change the search query arguments. The post_custom_fields sub-argument is used to define the custom fields to search. You can also check which fields are selected to search for via the post_fields argument.

Theoretically, you can use that to check if the “title” is selected for search, and add custom fields of your choice to the post_custom_fields array, something like this:

add_filter('asp_query_args', 'asp_add_fields_by_filters', 10, 1);
function asp_add_fields_by_filters( $args ) {
	// Title is selected for search
	if ( in_array('title', $args['post_fields'] ) ) {
		$args['post_custom_fields'] = array_unique(array_merge(
			args['post_custom_fields'],
			array('my_field_1', 'my_field_2') // -> add these fields for search
		));
		
		// Optionally, you can even unset the title from searching afterwards
		array_diff( $args['post_fields'], array('title') ); 
	}
	return $args;
}