public
Last active

Display some widgets from a sidebar in random order

  • Download Gist
gistfile1.aw
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
<?php
 
add_filter( 'sidebars_widgets', 'gmj_shuffle_widgets' );
/**
* Shuffle ranges of widgets within a sidebar.
*
* Hat-tip to {@link http://gmj.to/op} for the original idea.
*
* @uses gmj_do_shuffle_widgets() Does the actual array manipulation.
*
* @param array $sidebar_widgets Associative array of all sidebars and their widgets.
* @return array Amended array of all sidebars and their widgets.
*/
function gmj_shuffle_widgets ( array $sidebars_widgets ) {
 
// Only affect the front-end ordering
if ( is_admin() )
return $sidebars_widgets;
// Shuffle 2nd, 3rd and 4th widgets within the sidebar 'sidebar'
$sidebars_widgets = gmj_do_shuffle_widgets( $sidebars_widgets, 'sidebar', 2, 4 );
// Shuffle 5th and 6th widgets within the sidebar 'sidebar'
$sidebars_widgets = gmj_do_shuffle_widgets( $sidebars_widgets, 'sidebar', 5, 6 );
// Shuffle 1st, 2nd, 3rd, 4th and 5th widgets within the sidebar 'sidebar-alt'
$sidebars_widgets = gmj_do_shuffle_widgets( $sidebars_widgets, 'sidebar-alt', 1, 5 );
return $sidebars_widgets;
}
 
/**
* Shuffle a range of widgets in a sidebar.
*
* Could be generalised to shuffle a consecutive range of items in an array.
*
* @param array $sidebar_widgets Associative array of all sidebars and their widgets.
* @param string $sidebar The ID of the sidebar.
* @param integer $random_start The first widget to include in the shuffle.
* @param integer $random_end The last widget to include in the shuffle.
* @return array Amended array of all sidebars and their widgets.
*/
function gmj_do_shuffle_widgets( array $sidebars_widgets, $sidebar, $start, $end ) {
// Group into before, shufflable and after widgets
$head = array_slice( $sidebars_widgets[$sidebar], 0, $start - 1 );
$body = array_slice( $sidebars_widgets[$sidebar], $start - 1, $end - $start + 1 );
$tail = array_slice( $sidebars_widgets[$sidebar], $end );
// Mix those bad boys up
shuffle( $body );
 
// Put all the parts back together again
$sidebars_widgets[$sidebar] = array_merge( $head, $body, $tail );
 
// Send Humpty Dumpty back on his way
return $sidebars_widgets;
}

This is working great!
I was getting some error messages before I used the appropriate sidebar id. Duh!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.