Problem:
The customer wanted to filter a view on their website so that only specific URL parameters, such as "category=blog," remain visible in the URL after filtering. By default, all parameters were displayed, which cluttered the URL with unnecessary information.
Solution:
A combination of PHP and JavaScript was used to selectively retain only the category parameter in the URL after filtering. Here’s the implemented approach:
1- A hidden field was added to capture and maintain the category parameter, using a custom function in the theme’s functions.php file:
add_filter('wpv_filter_end_filter_form', 'add_hidden_category_param', 99, 4); function add_hidden_category_param($out, $view_settings, $view_id, $is_required) { $views = array(12345); // Replace with the View ID if (in_array($view_id, $views) && $is_required) { $category = isset($_GET['category']) ? $_GET['category'] : ''; $out = '<input type="hidden" id="category" name="category" value="' . esc_attr($category) . '" />' . $out; } return $out; }
This function captures the category parameter and stores it in a hidden input field to ensure it persists through the filter updates.
2- In the View's Custom JavaScript section, this code was added to ensure only the category parameter remains visible in the URL
jQuery(document).ready(function($) { $(document).on('js_event_wpv_parametric_search_form_updated', function(event, data) { var url = new URL(window.location); var category = url.searchParams.get("category"); jQuery('#category').val(category); // Update hidden input field with the category parameter // Update the URL to show only the category parameter let params = new URLSearchParams({ category: category }); window.history.replaceState({}, '', `${url.pathname}?${params.toString()}`); }); });
This JavaScript ensures the URL updates to include only the category parameter after filtering, creating a cleaner URL.
Relevant Documentation:
https://toolset.com/forums/topic/preserve-query-string-on-ajax-search
This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.
Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
- | 9:00 – 12:00 | 9:00 – 12:00 | 9:00 – 12:00 | 9:00 – 12:00 | 9:00 – 12:00 | - |
- | 13:00 – 18:00 | 13:00 – 18:00 | 13:00 – 18:00 | 13:00 – 18:00 | 13:00 – 18:00 | - |
Supporter timezone: America/Sao_Paulo (GMT-03:00)
This topic contains 1 reply, has 2 voices.
Last updated by 2 months ago.
Assisted by: Mateus Getulio.