Web Design & WordPress Blog

A recent client project required a custom post type to be ordered alphabetically and I wanted to share with you the function I used to accomplish this.

Rather than adding a query to the custom post archive template, I opted for an alternative which just required a snipped of code to be added to functions.php.

To order your custom post type alphabetically, simply add the following code to your themes functions.php file.


// Order custom post types alphabetically
function owd_post_order( $query ) {
    if ( $query->is_post_type_archive('my_custom_post_type') && $query->is_main_query() ) {
    $query->set( 'orderby', 'title' );
    $query->set( 'order', 'ASC' );
    }
}
add_action( 'pre_get_posts', 'owd_post_order' );

Once you’ve pasted this code into your functions.php file you will need to change ‘my_custom_post_type’ to the name of the custom post type you wish to re-order.

As always, be sure to back up your functions.php file before making changes in case of a problem and you need to revert back to the original file.

I hope you find WordPress code snippet this useful.

Thanks to Shipwreck for this snippet.

DiscussionLeave a comment

  1. Shaun says:

    That’s quite handy! Are you able to let me know where in my functions.php file I put the code? Thanks in advance.

    Shaun

    • Mark says:

      Hi Shaun, thanks for your comment. The easiest place to past the code would be right at the bottom. Then refresh the page which displays your custom posts and you should find they are now in alphabetical order. Make sure you make a backup copy of your functions.php file first though just in case you do experience a problem.

  2. Natasha says:

    Added the code to my functions file and it worked perfectly! Thank you so much!

  3. Rob says:

    Nice wordpress tip. Cheers for sharing buddy.

  4. Nell says:

    Good, helpful wordpress tip. Keep up the good work!