I couldn’t see that the answers in the possible duplicate link are using the sidebars_widgets
filter, so let me add it here as another possibility:
The following assumes you use dynamic_sidebar()
function to display your sidebars/widgets or just anything that calls the wp_get_sidebars_widgets()
function.
Randomize widgets:
This code snippet displays all the widgets in a random order:
/**
* Randomize widgets in a given sidebar (index)
*
* @See http://wordpress.stackexchange.com/a/152408/26350
*/
! is_admin() && add_filter( 'sidebars_widgets', function( $sidebars_widgets ) {
// ------------------------
// Edit this to your needs:
$sidebar_index = 'sidebar-1';
// ------------------------
if( isset( $sidebars_widgets[$sidebar_index] ) )
{
// Randomize the array:
shuffle( $sidebars_widgets[$sidebar_index] );
}
return $sidebars_widgets;
}, PHP_INT_MAX );
Randomize widgets – only display a single widget:
This code snippet only displays a single random widget:
/**
* Randomize widgets in a given sidebar (index) and only display a single widget
*
* @See http://wordpress.stackexchange.com/a/152408/26350
*/
! is_admin() && add_filter( 'sidebars_widgets', function( $sidebars_widgets ) {
// ------------------------
// Edit this to your needs:
$sidebar_index = 'sidebar-1';
// ------------------------
if( isset( $sidebars_widgets[$sidebar_index] ) )
{
// Randomize the array:
shuffle( $sidebars_widgets[$sidebar_index] );
// Slice the array:
$sidebars_widgets[$sidebar_index] = array_slice( $sidebars_widgets[$sidebar_index], 0, 1 );
}
return $sidebars_widgets;
}, PHP_INT_MAX );
You just have to remember to edit the $sidebar_index
to your needs.
I hope this helps.