X

Order Categories by Most Recently Updated

Snippets by IsItWP

Do you want to display a list of categories ordered by most recently updated category first? While there’s probably a plugin for this, we have created a quick code snippet that you can use to order categories by most recently updated in WordPress.

Instructions:

All you have to do is add this code to your theme’s template file or in a site-specific plugin:

<?php
    $cat_array = array();
    $args=array(
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => 20,
      'caller_get_posts'=> 1
      );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post();
        $cat_args=array('orderby' => 'none');
        $cats = wp_get_post_terms( $post->ID , 'category', $cat_args);
        foreach($cats as $cat) {
          $cat_array[$cat->term_id] = $cat->term_id;
        }
      endwhile;
    }
    if ($cat_array) {
      foreach($cat_array as $cat) {
        $category = get_term_by('ID',$cat, 'category');
        echo '<a href="' . esc_attr(get_term_link($category, 'category')) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>'.'<br />';
      }
    }
    wp_reset_query();
?>

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: How to create a contact form in WordPress and 12 best WordPress podcast plugins.

Comments   Leave a Reply

  1. This function does not work!!

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!