How to Limit the number of order indexes in post queries

Last updated on: December 4, 2025 10:44 am

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPrint this page

When Auto Sort is enabled, the Advanced Post Types Order plugin applies the custom order automatically on the front end. It’s easy to use and requires no coding: the custom order is injected into any front-end or dashboard query that matches the sort settings.

On very large sites (hundreds of thousands of posts), including the full order index list in every query can have a small performance impact. Because a single page load typically runs multiple queries, the impact can add up. Fortunately there’s a simple solution: a filter lets you use only a portion of the full order list. By default the plugin uses the first 1,000 indices from the order list; remaining posts fall back to the standard ordering by post date.

    add_filter( 'apto/get_orderby',     'apto_get_orderby', 10, 5 );
    function apto_get_orderby( $new_orderBy, $orderBy, $sort_view_id, $query, $order_list = FALSE )
        {
            global $wpdb;
            
            if ( $order_list === FALSE )
                return $new_orderBy;
            
            //Only on front side
            if  ( is_admin() ) 
                return $new_orderBy;
 
            $_LimitIndexLiatTo  =   1000;
            
            $order_list =   array_slice( $order_list, 0, $_LimitIndexLiatTo ); 
            
            $query_order = isset($query->query['order']) ? strtoupper($query->query['order']) : 'ASC';
            
            $counter = 0;
            
            $orderBy = "CASE ";
            foreach ( $order_list as $value )
                {
                    $counter++;
                    $orderBy .= " WHEN ". $wpdb->posts .".ID = ". $value ."  THEN  ". $counter;   
                }
            
            $counter++;
            if (  $query_order  ==  'DESC')
                $counter    =   0;
            $orderBy .= " ELSE ". $counter ." END, ".$wpdb->posts.".post_date " . $query_order;
                        
            return $orderBy;   
        }
  • *The above code should be placed into theme functions.php or a file into wp-content/mu-plugins/

Important to understand the query ‘order’ argument, which usually should be the default ‘ASC’, or the list will be reverted.