I have a WordPress website with header.php
called for every single page. On header.php
, I have a form on which the user can select a product category. On change, the form will redirect the user to my category page, which is category.php
on my server but appears as /category when browsing the site.
On header.php:
<form method="POST" action="category" id="cateogry-filter-pick">
<select class="selectpicker" id="category-filter" name="cat">
<?php
$category_list = $wpdb->get_results("SELECT DISTINCT product_category FROM $table_name;");
foreach($category_list as $key => $row): ?>
<option value="<?php echo str_replace(' ', '-', $row->product_category);?>"><?php echo $row->product_category;?></option>
<?php endforeach; ?>
</select>
</form>
on Custom-js.js
$(function(){
$('#category-filter').on('change', function() {
this.form.submit();
});
});
On category.php, I can asign the category to a variable, and then loop to display all my results, using:
$product_category = isset($_POST['cat']) ? $_POST['cat'] : null;
On my category page, I am also using some sorting filters with AJAX / $_GET, which would change the URL to something like this:
/category/?sort=rating
When doing so, I lose the value of the category sent from any previous $_POST
.
What I would ultimately want to do is to change my page URL from /category
to /the-name-of-the-category/
(which is $_POST['cat']
) and preserve this value when I use my sort filters. My URL would then become something like:
www.mywebsite.com/shoes/?sort=rating
What is the best approach to do so, considering that I also want users who type a URL in their browser such as www.mywebsite.com/shoes
to access the same page.