It took me quite a while to find a good solution for ordering a custom post type by two custom meta keys. When I finally got it working, I found out the pagination no longer works. I've tried dozens of different code snippets found online but nothing has fixed my unique. I would appreciate any help I can get, or if you think rewriting would work, please provide me examples of a better way to do this.

I have a custom post type named Episodes. These have season and episode numbers that I wish to sort by.


if ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; }
$args = array(
  'post_type' => 'episodes',
  'paged' => $paged,
  'posts_per_page' => 10,
  'orderby' => 'meta_value',
  'meta_key' => 'season_number',
  'meta_query' => array(
            'key' => 'season_number',
            'value' => '',
            'compare' => 'LIKE'
            'key' => 'episode_number',
            'value' => '',
            'compare' => 'LIKE'
if ( have_posts() ) : ?>

    <?php /* Start the Loop */ ?>
    <?php while ( have_posts() ) : the_post(); ?>


add_filter('posts_orderby', 'edit_posts_orderby');
function edit_posts_orderby($orderby_statement) {
    if(is_post_type_archive('episodes')) {
        $orderby_statement = "mt1.meta_value, mt2.meta_value DESC";
        return $orderby_statement;

I am aware that Query_Posts on an archive page is NOT best of practices, but I couldn't make the ordering work using pre_get_posts. If someone knows how to rewrite it to work in pre_get_posts I'm willing to try it. I understand my pagination may work again just by switching but I'm just not sure how to.


  • Please read this, and try to use pre_get_posts. Does it work now?
    – fuxia
    Apr 22, 2013 at 20:08

1 Answer 1


I've battled with a similar problem and came to the conclusion that you can't order by multiple meta values properly using pre_get_posts.

However in your case the solution might actually be very simple. All you need to do is combine the season number with the episode number into a single number.

I don't know how the user enters these values, but if its done via a custom meta box, then this can be done easily on the function that saves the custom meta values to the database.

Once you've prepared the data this way, you only need to orderby by meta_value_num via pre_get_posts. Like this you won't have to use query_posts() and the pagination and other functionalities will work as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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