Skip links

How to: Order WordPress custom post types on an archive page

Blog

Learn more about how we work and what we have been working on lately.

How to: Order WordPress custom post types on an archive page

20 June

A quick tip on how to order custom post types on a WordPress archive page.

If you are struggling to find a way to order WordPress custom post type posts on an archive page, this might help.

First of all make sure you have added ‘page-attributes’ in your post type function:


'supports' => array('title','editor','thumbnail','excerpt','custom-fields','revisions','page-attributes'),

This adds the ‘Order by’ attribute on the CPT admin edit page. This is where you give the post a number by which you can order them.

Then create a new function like below:


function ifamily_cpt_order( $query ) {
    if ( is_admin() || ! $query->is_main_query() )
        return;
    if ( is_post_type_archive( 'country' ) || is_tax( 'county' )) {
        // Display 10 posts for a custom post type called 'country' or a taxonomy called 'county' ordered by order value attribute
        $query->set( 'orderby', 'menu_order', 'order','ASC','posts_per_page', 10 );
        return;
    }
}
add_action( 'pre_get_posts', 'ifamily_cpt_order', 1 );

The if statement checks to see if the archive is a ‘country’ custom post type or a taxonomy called ‘county’.

The section which orders the custom post types is this line:


$query->set( 'orderby', 'menu_order', 'order','ASC','posts_per_page', 10 );

As an added bonus you can add this code to your funtions.php page to the admin so that you can sort by order number in the admin too.


/**
* add order column to admin listing screen for country
*/
function add_new_country_column($country_columns) {
  $country_columns['menu_order'] = "Order";
  return $country_columns;
}
add_action('manage_edit-country_columns', 'add_new_country_column');
/**
* show custom order column values
*/
function show_order_column($name){
  global $post;
  switch ($name) {
    case 'menu_order':
      $order = $post->menu_order;
      echo $order;
      break;
   default:
      break;
   }
}
add_action('manage_country_posts_custom_column','show_order_column');
/**
* make column sortable
*/
function order_column_register_sortable($columns){
  $columns['menu_order'] = 'menu_order';
  return $columns;
}
add_filter('manage_edit-country_sortable_columns','order_column_register_sortable');

Hope this helps!

Tags: , ,

Powered by WordPress.