WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 4 down vote accepted

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>
        <input type="hidden" name="cs_action" value="custom_sort_order">
        <input type="submit" name="submit" value="sort">

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.

share|improve this answer
You are the best! Anyway if I choose A-Z it "sorts" posts from the first one published to the last one and if I choose Z-A it shows them from the last one to the first. What I would like to do is to sort them in alphabetical order, is it possible? – Downloadtaky Apr 27 '11 at 22:30

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.