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">
                <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>

    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