Adding another search field in a custom search box

To add a dropdown selector for the custom field meta key “function_camere” in your WordPress search form, you can modify the wpb_demo_shortcode function to include this new dropdown. This dropdown will allow users to select a value for the “function_camere” field, which will then be used as a search criterion.

Here’s how you can modify the wpb_demo_shortcode function to include this functionality:

First, you need to retrieve the unique values for the “function_camere” custom field from the database. This will populate the dropdown options.
Add a new dropdown to the form for the “function_camere” field.
Modify the form submission to include this new criterion in the search query.
Below is the updated code for the wpb_demo_shortcode function:

function wpb_demo_shortcode() {
    global $wpdb, $wp_query;

    // Retrieve categories dropdown
    $categories = wp_dropdown_categories([
        'show_count' => 1,
        'hierarchical' => 1,
        'show_option_all' => esc_html__('All destinations', 'sacconicase'),
        'echo' => false,
    ]);

    // Retrieve tipologia dropdown
    $select = $wp_query->get('tipologia');
    $select="" == $select ? 0 : $select;
    $taxonomy = wp_dropdown_categories([
        'hierarchical' => false,
        'name' => 'tipologia',
        'taxonomy' => 'tipologia',
        'selected' => $select,
        'show_option_all' => esc_html__('Typology', 'sacconicase'),
        'value_field' => 'slug',
        'echo' => false
    ]);

    // Retrieve unique values for 'function_camere' custom field
    $functionCamereValues = $wpdb->get_col("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'function_camere' ORDER BY meta_value");
    $functionCamereDropdown = '<select name="function_camere">';
    $functionCamereDropdown .= '<option value="">' . esc_html__('Select Function Camere', 'sacconicase') . '</option>';
    foreach ($functionCamereValues as $value) {
        $functionCamereDropdown .= '<option value="' . esc_attr($value) . '">' . esc_html($value) . '</option>';
    }
    $functionCamereDropdown .= '</select>';

    // Form output
    $output="<form class="sacconi_form" method="get" action="" . home_url("https://wordpress.stackexchange.com/") . '">' .
              $categories . $taxonomy . $functionCamereDropdown . '<br><br>' .
              '<input type="submit" name="search" value="' . esc_html__('Search', 'sacconicase') . '">' .
              '</form>';

    return $output;
}

add_shortcode('ricerca', 'wpb_demo_shortcode');

This code creates a dropdown for the “function_camere” custom field, populated with its unique values. Users can select an option from this dropdown along with other criteria to refine their search. The form method is corrected to method=”get” for proper submission. Ensure that the search results page handles this new query parameter appropriately.

tech