0

I'm trying to sort a custom post type in ascending order (instead of the default descending). Registering the post type like so:

function codex_custom_init() {

  register_post_type(
    'calendar', array(
      'labels' => array('name' => __( 'Calendar' ), 'singular_name' => __( 'Calendar' ) ),
      'public' => true,
      'has_archive' => true,
      'rewrite' => array('slug' => 'calendar'),
      'supports' => array('title', 'editor', 'thumbnail'),
      'orderby' => 'date',
      'order' => 'ASC'
    )
  );                      

}

But for some reason 'order' => 'ASC' isn't working? It's probably something I'm doing wrong, but is there anyway of achieving this?

6

You don't declare the order of the results when you register the post type.

Instead, you do at the time the results are requested. If you're using WP_Query to get the results then you add your orderby and order arguments to the request.

http://codex.wordpress.org/Class_Reference/WP_Query

If you want to change the order of the results on the archive pages such as http://www.yoursite.com/calendar/ then you have to filter the existing query by can using the pre_get_posts filter like so:

function wpse_167441_reorder_calendar($query) {
  if ( !is_admin() && $query->is_main_query() ) {

    if (is_post_type_archive('calendar')) {
      $query->set('orderby', 'date' );
      $query->set('order', 'ASC' );
    }

  }
}

add_action('pre_get_posts','wpse_167441_reorder_calendar');

If you want this to be the case in the admin area too then you can remove the !is_admin check. Be sure to test that you have not effected other post types when you're doing this - that's why the is_post_type_archive condition is in there.

http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts

Hope that's what you were after.

1

Please note: This is just an extension to the other answer

As already mentioned in the other answer, orderby and order are invalid arguments supplied for register_post_type

You should take your time and work through the link provided above.

I just also want to raise this, you cannot use calender as your post type name. It is a reserved name.You will have to rename your custom post type, you can maybe use the plural name, calenders. You should read through the list given to make sure that you don't use any of those names as taxonomy or post type names

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.