Change Category Sort Order

It is strange that there is no option to reverse the display order of the posts on the category page, when we select a category the list is the same as a blog, in descending order newest to oldest.

That is great for a news or magazine website, but what if we wanted to display a series of our posts in ascending order, for a tutorail with the oldest part one first?

The easy ‘no code way’ if we do not have many to deal with, is just to alter the dates and times on the posts to reverse the order.

A simples code way is just to add a call before the loop in the category.php file, this will work on all categories though, we could alse code to find the category and add a string of ‘if  elseif’ statements.

<?php query_posts($query_string . "&order=ASC"); ?>

Our Option

We want to empower the website administrators to be able to select which categories they want to sort in a ascending order, we also want to do this on the category edit page by a simple dropdown selector.

If we look at what we have now there is no way to change the sort order on the ‘Add New Category’ page, so we will add the option to the edit Category page.

asc-1

If we look at the posts in the aciform category we can see the latest post was Lorum Ipsum, this could be lesson 4 in a series of tutorials, we want to reverse this sort order.

asc-2

We have as always created a twenty ten child theme, but this can be added in minutes to an artisteer or many other themes, all we need to do is add a folder and two bits of code.

Download the twenty ten child theme here: Twenty Ten Category Sort (647)

Activate the child theme on a local install, navigate to Admin > Posts > Categories

From the list choose any category and edit, see the new option ‘Sort Order’, we used code from a this post we found online and changed the code for this post.

We prefer to work with a single array option, as this is more inline with how WordPress ask us to develop now, rather than one option per category, so we have reworked the code.

asc-3 If we change the sort order to ascending we can now see the order has been reversed, pretty effective.

asc-4

Adding the functions to a Theme

In the download there is a folder called /includes/ and inside the folder is a file called category-functions.php drop the sub folder into the theme’s folder, as in the download.

Two bits of code to add first open functions.php and add in this code block, the first line is a bit of shorthand code, this checks to see it it is a child or parent theme and returns the file name and path.

The second line just looks to see if the file exists, if it is then include it, the last line just returns the stored options into a global variable if they exists.


$filename=( is_child_theme() ) ? STYLESHEETPATH .'/includes/category-functions.php' : TEMPLATEPATH .'/includes/category-functions.php';
if( file_exists($filename) ) include_once( $filename );

$cat_meta = get_option("theme_cat_meta");

Category Page

Next in the themes folder we should have a file category.php open this file and find the get_template_part( ‘loop’,’category’ ) just before this line we want to add another block of code.

This bit of code looks to see if the category meta is set and if it is ‘ASC’, if it is it just reverses the sort order.


<?php
 /* Start Reverse Posts */
 global $cat, $cat_meta;
 if (isset( $cat_meta[$cat]['order'] ) &&  $cat_meta[$cat]['order'] == 'ASC' ) query_posts($query_string . "&order=ASC")
 /* End Reverse Posts */
 ?>

Other Themes

If you have Artisteer or you do not have the template part, or you can not find category.php just save index.php as category.php, open the new file.

Add the code before the if( have_posts() )

<?php
 /* Start Reverse Posts */
 global $cat, $cat_meta;
 if (isset( $cat_meta[$cat]['order'] ) &&  $cat_meta[$cat]['order'] == 'ASC' ) query_posts($query_string . "&order=ASC")
 /* End Reverse Posts */
 ?>

<?php
 if(have_posts()) {

Warning: careful with the php tags, if you are already inside an unclosed <?php tag then you do not need the tags from the new code above.

Conclusion

Inside the file category-functions.php there are two functions, one to add the meta box to the Edit Category page, the other to set the $cat_meta array and store in in a WordPress option, we are not looking at that code as it is covered in the link above.

We now can set the sort order for any category on our website, why it is not already built in, who knows?

category-functions.php

For reference here is the contents of the file:

<?php

add_action ( 'edit_category_form_fields', 'extra_category_fields' );
function extra_category_fields( $tag ) {
 global $theme_css, $cat_meta;
 $t_id = $tag->term_id;
 $curr_meta = $cat_meta[$t_id];
 $direction=( $curr_meta && isset( $curr_meta['order'] ) && $curr_meta['order'] ) ? $curr_meta['order'] : "DESC";
?>

<?php
$sort_order = array(
 'DESC' => array(
 'value' => 'DESC',
 'label' => 'Descending'
 ),
 'ASC' => array(
 'value' => 'ASC',
 'label' => 'Ascending'
 ),
);
?>

<tr>
 <th scope="row" valign="top"><label for="cat_meta[order]"><?php _e('Sort Order'); ?></label></th>
 <td>
 <select id="cat_meta[order]" name="cat_meta[order]">
   <?php
   foreach ( $sort_order as $option ) :
     $label = $option['label'];
     $selected = '';
     if ( $direction && $direction ==  $option['value'] ) $selected = 'selected="selected"';
     echo '<option style="padding-right: 10px;" value="' . esc_attr( $option['value'] ) . '" ' . $selected . '>' . $label . '</option>';
   endforeach;
   ?>
 </select>
 </td>
 </tr>
<?php
}

add_action ( 'edited_category', 'save_extra_category_fields');
function save_extra_category_fields( $term_id ) {
 global $cat_meta;
 if ( isset( $_POST['cat_meta'] ) ) {
   $t_id = $term_id;
   $cat_keys = array_keys($_POST['cat_meta']);
   $curr_meta = array();
   foreach ($cat_keys as $key){
     if (isset($_POST['cat_meta'][$key])){
       $curr_meta[$key] = $_POST['cat_meta'][$key];
     }
   }
   $cat_meta[$t_id] = $curr_meta;
   update_option( "theme_cat_meta", $cat_meta );
 }
}
?>

Notices

We do require your feedback to improve our themes and tutorials, please leave your comments good or bad.

Code disclaimer information

If this document contains programming examples, www.DigitalRaindrops.net grants you a nonexclusive copyright license to use all programming code from which you can generate similar functions tailored to your own specific needs.

All sample code is provided by http://DigitalRaindrops.net for learning illustrative purposes only.

These examples have not been thoroughly tested under all conditions. www.DigitalRaindrops.net, therefore, cannot guarantee or imply reliability, serviceability, or function of these examples.

All programs contained herein are provided to you “AS IS” without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.

Membership

Registration and Membership is no longer required for downloading files or interacting with Digital Raindrops, posting a comment or topic in the forum does use Captcha to reduce spammers.

This website is a tool to support and promote WordPress and Artisteer theme development, please support, share and give credit for any benefits you gain from the tutorials on this website.

One thought on “Change Category Sort Order

  1. I know nothing about PHP and that sort of thing, so I would never be able to do this. However, I just wanted to say that I think this is amazing. You say that it is strange that this option is not standard in WordPress. I would say that it is incredible, if not insane that it isn’t standard.

    I’ve been banging my head against the wall trying to imagine why such simple – yet universally useful – things are not part of WordPress. To list all posts all the time in reverse chronological order strikes me as totally illogical. I’m constantly reading travel blogs where I have to go to the end and then read backward one post at a time, constantly skipping up one and reading down and then going up two and reading down, etc. It’s crazy.

    Can the code you wrote above be applied to all themes? I am currently using the Arthemia theme from ColorLabs, and I would LOVE to be able to have the option to sort certain Categories in ascending or descending order by date. Perhaps I can find an expert to take your code and put it into my theme for me.

    Any advice?

    Thanks!
    Doug

Leave a Reply

Connections

Connect with Us
Follow Digital Raindrops on Twitter Join Digital Raindrops on Facebook
Share

Related Posts

Posted in Tips

colorizer-1_thumb.png

We thought we would use the WordPress Twenty Eleven theme and the the Farbtastic color picker to colorize our theme from the website front page instead of the admin area. We have been looking at the $_SESSION variable, so we thought … Continue reading

Read More

Posted in Twenty Ten

catlist_thumb

This is a short post, the code is in the child theme download, just two files a page and a loop, on the Artisteer forum someone was asking about having a list of child categories in the page body, one … Continue reading

Read More