How to let users choose posts order in categories?
-
16-10-2019 - |
Question
I'm running a wordpress based website and I need to let the users choose how to show the posts inside categories pages.
I would like to have a button inside a category page that can be clicked so the reader can choose if he wants to see posts ordered by date or from A to Z or from Z to A.
Is there anyone who can tell me how to achieve this? Please explain it like if you are speaking to your 12 years son :-) I google a lot about this and I've never found nothing that I can copy/paste into my code or that I can modify. I can't understand how to do this... any solution?
Solution
First in your category.php (depending on your theme files) add a simple form to let the user sort A-Z or Z-A:
<form action="" name="custom_order" method="POST">
<p> sort order:
<select name="CU_Order" id="CU_Order">
<option value="ASC">A-Z</option>
<option value="DESC">Z-A</option>
</select>
</p>
<p>
<input type="hidden" name="cs_action" value="custom_sort_order">
<input type="submit" name="submit" value="sort">
</p>
</form>
then using pre_get_posts
hook you alter the query to order like the user has selected:
add_action( 'pre_get_posts', 'change_sort_order' );
function change_sort_order(&$query){
if (isset($_POST['cs_action']) && $_POST['cs_action'] == 'custom_sort_order'){
global $wp;
if (isset($wp->query_vars["CU_Order"])){
$query->set( 'order', $wp->query_vars["CU_Order"] );
}
}
}
and all that is left is to add CU_Order
order to the list of query vars WordPress knows using query_vars
hook:
add_filter('query_vars', 'add_custom_order_query_vars');
function add_custom_order_query_vars($vars) {
// add CU_Order to the valid list of variables
$new_vars = array('CU_Order');
$vars = $new_vars + $vars;
return $vars;
}
simpler explanation:
copy the first code in your category.php
copy the rest in to your theme's functions.php
Done.