Automatically Randomize a sort list while keeping the sticky posts on top

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

Through the Automatic Order functionality, the Advanced Post Types Order plugin provide an excellent support for post objects sorting automatization. Using default functions, easy order can be set by ID, Author, Title, Slug, Date, Modified Date, Comments Count etc. Also Custom Fields sorting can be easily set-up by specify the custom fields keys.

Effortlessly infuse a touch of randomness into your post sorting by selecting the ‘Random’ option through the Automatic Order feature. However, it’s worth noting that this action shuffles all posts in the list, without maintaining a fixed position for any specific post.
In scenarios where Sticky Posts need to retain their defined positions in the list while the others are randomized, a more tailored approach is required. This nuanced functionality can be seamlessly implemented using the User Function Callback along with a bit of custom code. This strategic combination allows you to achieve a balanced mix of randomness and control, offering a more refined and personalized sorting experience for your posts.

We create a new function (usually within theme function.php or a custom plugin) called randomize_order_with_sticky_on_top then ensure the Custom Function field held that key:

Then within the theme function.php we add the following code:

    function randomize_order_with_sticky_on_top ( $post_list, $sort_view_id, $orderBy, $query )
        {
            shuffle($post_list);
                
            //retrieve the sticky list for current sort ID
            $sticky_list = get_post_meta( $sort_view_id , '_sticky_data', TRUE);
            
            if ( ! is_array ( $sticky_list )    ||  count ( $sticky_list ) < 1 )
                return $post_list;    
                
            //remove the sticky items in the $post_list
            foreach ( $sticky_list as $position => $object_id ) 
                {
                    if ( isset ( $post_list [ $object_id ] ) )
                        unset ( $post_list [ array_search( $object_id, $post_list ) ] );
                }
            
            $post_list  =   array_values ( $post_list );
                    
            foreach ( $sticky_list as $position => $object_id ) 
                {
                    // Insert the ID at the specified position
                    array_splice( $post_list, $position - 1, 0, $object_id );
                }

            return $post_list;
                
        }

Once set-up completed, the front side sorting will change accordingly to above functionality.