Add ZIP to Search
November 19, 2024 ยท AI Conversations
1. **Create a Custom Field for ZIP Code:**
– Go to **GeoDirectory > Fields**.
– Add a new field for ZIP Code if it's not already there. Choose the field type as **Text** or **Postal Code**.
– After creating the field, make sure to assign it to the relevant post type (like `Listing`).
2. **Modify the Search Form:**
– To add the ZIP code field to the search form, you'll need to modify the search template.
– If you're using the default GeoDirectory search form, you can override the search form template by creating a custom template in your theme. Copy the template file `wp-content/plugins/geodirectory/templates/geo-directory/search/search-form.php` into your theme directory: `wp-content/themes/your-theme/geo-directory/search-form.php`.
3. **Edit the Search Form Template:**
– In the copied `search-form.php` file, look for the form structure. Add an input field for the ZIP code where you want it to appear.
– Example:
<div class="geodir-search-field">
<label for="zip_code"><?php _e('ZIP Code', 'geodirectory'); ?></label>
<input type="text" name="geodir_zip_code" id="zip_code" value="<?php echo isset($_GET['geodir_zip_code']) ? esc_attr($_GET['geodir_zip_code']) : ''; ?>" placeholder="Enter ZIP code" />
</div>
4. **Modify the Search Query:**
– To ensure the search respects the ZIP code input, you'll need to hook into the GeoDirectory search query and filter it by the ZIP code.
– Add this code to your theme's `functions.php` file:
add_filter('geodir_search_query', 'filter_search_by_zip_code', 10, 2);
function filter_search_by_zip_code($args, $form_data) {
if (!empty($_GET['geodir_zip_code'])) {
$zip_code = sanitize_text_field($_GET['geodir_zip_code']);
$args['meta_query'][] = array(
'key' => 'your_zip_code_meta_key', // Replace with the actual meta key for the ZIP code field
'value' => $zip_code,
'compare' => 'LIKE',
);
}
return $args;
}
– Replace `your_zip_code_meta_key` with the actual meta key used for storing the ZIP code in your listings.
5. **Test the Search Form:**
– After making these changes, test the search functionality to make sure the ZIP code filter is working correctly in the form.
This will allow users to enter a ZIP code into the search form and filter the results based on the ZIP code entered.