Skip to content

Instantly share code, notes, and snippets.

@GaryJones
Created December 24, 2011 15:26
Show Gist options
  • Save GaryJones/1517555 to your computer and use it in GitHub Desktop.
Save GaryJones/1517555 to your computer and use it in GitHub Desktop.
Display some widgets from a sidebar in random order
<?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;
}
@kalligator
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment