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 automatisation. 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.

Randomizing sort list through automatic order is very easy, this can be achieved through selecting the Random option. However all posts in the list will be shuffled, so there is fixed position for any of the posts. IN some cases the Sticky Posts are required to stay on top of list while the other posts will be randomized. This functionality can be implemented through the User Function Callback and a bit of code.

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 the list
            shuffle($post_list);
            
            //retrieve the sticky posts list
            $sticky_posts   =   (array)get_option('sticky_posts');
            
            if ( count ( $sticky_posts )    <   1 )
                return $post_list;
            
            $found_sticky_posts =   array();
            $found_sticky_posts =   array_intersect($sticky_posts, $post_list);
            
            if ( count ( $found_sticky_posts )    <   1 )
                return $post_list;
            
            //remove from the list
            foreach($found_sticky_posts as  $found_sticky_post)    
                {
                    unset( $post_list  [ array_search( $found_sticky_post, $post_list ) ] );
                }
                
            array_unshift($post_list, $found_sticky_post);
            
            //reindex the array
            $post_list  =   array_values( $post_list );
            
            return $post_list;
                
        }

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