Created
December 24, 2011 15:26
-
-
Save GaryJones/1517555 to your computer and use it in GitHub Desktop.
Display some widgets from a sidebar in random order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is working great!
I was getting some error messages before I used the appropriate sidebar id. Duh!