Lookhappy Design

24 December 2014

Custom post type orderby menu_order not working?

So this seems like it should be straight forward – you’ve created your custom post type within wordpress, but for some reason your template is totally ignoring your orderby commands. You try setting it to orderby=menu_type, or orderby=ID, but nothing seems to make a difference.

Well here’s the thing – you may not have created your custom post type quite right afterall.
So let’s just check a working custom post type script (this goes within your functions.php file)

add_action('init', 'courses_items');
// Creates courses_items post type
function courses_items() {
register_post_type('courses_items', array(
'label' => 'Events',
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => true,
'rewrite' => array('slug' => 'whats_on'),
'query_var' => true,
'has_archive' => true,
'supports' => array(
)); }

The important bit there is the ‘hierarchical’ => true and the ‘has_archive’ => true without these two lines you can’t order by menu_order.
Once you’ve sorted that you can display them as normal, with code such as this in your template:

<?php query_posts('showposts=-1&post_type=courses_items&orderby=menu_order&order=ASC'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
// Code to display your custom posts goes here
<?php endwhile; endif; wp_reset_query(); ?>