How to randomize the first 10 posts in a manually sorted list

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

The first step will be to create a sort which match a specif area of the site. Any sort type can be used either simple sort or mix of taxonomies and post types.

Further, the following code should be placed inside theme functions.php or a custom plugin. The $SORT_TO_MATCH ne to be changed with the sort ID previously created, also $RANDOMIZE_FIRST_X_POSTS should contain the number of posts to randomize:

    add_filter('apto/get_order_list', 'custom_apto_get_order_list', 10, 2);
    function custom_apto_get_order_list( $order_list, $sort_view_id )
            $SORT_TO_MATCH              =   121;
            $RANDOMIZE_FIRST_X_POSTS    =   10;
            $sort_view_post =   get_post( $sort_view_id );
            if ( $sort_view_post->post_parent   !=  $SORT_TO_MATCH)
                return $order_list;
            //randomize the first 10 posts
            $slice  =   array_slice( $order_list, 0, $RANDOMIZE_FIRST_X_POSTS);
            shuffle( $slice );
            //add the values
            foreach  ( array_values($slice) as $key    =>  $value)
                    $order_list[$key]   =   $value;
            return $order_list;

Notify of
Inline Feedbacks
View all comments