Customize post type archive order

By now you’re probably already familiar with one of WordPress’ most loved features, custom post type. A custom post type could be hierarchical (like page) or non-hierarchical (like post). This snippet will modify the default posts order when the post type archive is being displayed.

Note:
Instead of adding these snippets into your theme’s functions.php file, I really recommend creating a mu-plugin file, so you will always get the functionality, no matter what theme you’re currently using (IMO, themes shouldn’t interfere with this kind of functionality anyway).

Register Post Type

For this to work, there are three things we need to pay attention to when registering our post type; it has to be set to hierarchical, it has to support page-attributes, and it has to support archive.

function my_custom_post_types_register() {
  register_post_type('work', array(
    'labels'        => array('name' => __('Works'), 'singular_name' => __('Work')),
    'public'        => true,
    'hierarchical'  => true,
    'supports'      => array('title', 'editor', 'thumbnail', 'page-attributes'),
    'has_archive'   => true,
    'rewrite'       => array('slug' => 'work', 'with_front' => false)
  ));
}
add_action( 'init', 'my_custom_post_types_register' );

Customize archive order

function my_custom_archive_order( $vars ) {
  if ( !is_admin() && isset($vars['post_type']) && is_post_type_hierarchical($vars['post_type']) ) {
    $vars['orderby'] = 'menu_order';
    $vars['order'] = 'ASC';
  }

  return $vars;
}
add_filter( 'request', 'my_custom_archive_order');

The code should be pretty self-explanatory; we will only modify the order if we’re on the front-end, and we’re viewing a hierarchical post type archive.

Actually, the hierarchical mode is not really needed for this, since custom-ordering posts can always be done if the post type supports page-attributes. However, IMO, custom order doesn’t really make sense for non-hierarchical posts, don’t you think? 🙂

If you don’t want to set the post type to hierarchical, just replace the third logic in my_custom_archive_order, so it would check if the post type supports page-attributes:

if ( !is_admin() && isset($vars['post_type']) && post_type_supports($vars['post_type'], 'page-attributes') ) {
//...
}

To reorder the posts, you can manually edit their orders one by one, or use this plugin (only if you don’t have/need child pages, since it doesn’t support it yet).

Example? Try this 🙂

Customize post type archive order

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.