Home › Forums › ACF PRO › Search form with meta_field › Reply To: Search form with meta_field
For those who are interested in using the WP search to search for a value in a meta field, see the code below. Ofcourse adding 1 line to a form needs less code and is thus a lot less error prone.
This is the search form. In my case I want to search for name only, so I added line 4 to uniquely identify this search form (so pre_get_posts won’t be applied to all search queries).
<form class="form form--search" action="" method="post">
<fieldset>
<div>
<input type="hidden" name="name_search" value="1" />
<input type="search" name="s" class="search__input" placeholder="Search for a name" />
<button type="submit" class="button button--submit">Submit</button>
</div>
</fieldset>
</form>
Then add this to functions.php:
function search_filter_for_name( $query ) {
if ( ! is_admin() && $query->is_main_query() && isset( $_POST['name_search'] ) && 1 == $_POST['name_search'] ) {
if ( $query->is_search ) {
// set search string to false, otherwise the search searches in the_content() for this phrase and I want a specific field only
$query->set( 's', false );
// set your desired post type(s)
$query->set( 'post_type', array( 'your_post_type' ) );
// set the meta query for your specific field
$query->set( 'meta_query', array(
'key' => 'field_name',
'value' => $query->query['s']
) );
}
}
}
add_action( 'pre_get_posts', 'search_filter_for_name' );
my initial question still stands
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.