Search Custom Post Type Pages and Custom Fields in 2 Dropdowns?

Looks like this question is a several months old, but it’s a good one so I’m digging it out of the grave.

The way I would go about solving it would be to intercept any searches with the pre_get_posts filter and add in the meta query based on the provided information. Here’s a basic shot at the solution, which can become a plugin or go in your theme’s functions.php file:

<?php
/**
 * Add a parameter for a custom field search
 */
add_filter('query_vars', 'wpse_35639_search_queryvars' );
function wpse_35639_search_queryvars( $qvars ) {
    $qvars[] = 'bedrooms';
    return $qvars;
}


/**
 * Intercept the posts query to add in our meta query if necessary
 */
add_action('pre_get_posts','wpse_35639_intercept_search');
function wpse_35639_intercept_search() {
    global $wp_query;

    if ( ! is_admin() && isset($wp_query->query_vars['bedrooms']) && is_numeric($wp_query->query_vars['bedrooms']) ) {
        # Limit the search to the floor_plan custom post type
        $wp_query->set('post_type', 'floor_plan');

        # This may seem unconventional, but we're setting that this is a search
        # even though WP doesn't recognize it as one. This is to leverage the search template
        $wp_query->is_search = true;

        # Set the meta query comparison
        $wp_query->set('meta_query', array(
            array(
                'key' => 'number_of_bedrooms',
                'value' => $wp_query->query_vars['bedrooms'],
                'compare' => '=',
                'type' => 'NUMERIC'
            )
        );
    }
}
?>

Note that this just solves the custom field portion of the search. Searching by page is much easier (and I gather you solved that already).

Leave a Comment