Question

I'm creating a custom WordPress template which has 4 "sidebars" one for the header, a separate sidebar for the left and right columns, and then another sidebar for the footer, all that's fine and working properly. However, with my template, the header sidebar can only hold one widget at a time, so I was wondering if there was a way to add multiple widgets to the sidebar, but manipulate the code somehow to only display a random (or even in some specific order) widget at a time, which will change on each new page reload.

Code I used to make the sidebar:

if (function_exists('register_sidebar')) {
    register_sidebar(array(
        'name' => 'Header Sidebar Widgets',
        'id'   => 'sidebar-widgets-header',
        'description'   => 'The Header Can Only Support One (1) Widget.',
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2>',
        'after_title'   => '</h2>'
    ));
}

And then the code I used to add the sidebar to my template:

if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar-widgets-header') ) :
endif;

Here is an image of the sidebar within my admin currently:

Sample
(source: illstudios.com)

Quote One and Featured Videos are custom widgets I created. So is there a way to only choose one random widget from the selection and only display one widget at a time?

Was it helpful?

Solution

There's a filter that returns all widgets in all sidebars. We can shuffle and trim one of the sidebars with it:

if( !is_admin() )
{
    add_filter( 'sidebars_widgets', 'sidebar_so_23691473' );
}

function sidebar_so_23691473( $sidebars_widgets )
{
    shuffle( $sidebars_widgets['sidebar-widgets-header'] );
    $only_one = array_slice( $sidebars_widgets['sidebar-widgets-header'] , -1 );
    $sidebars_widgets['sidebar-widgets-header'] = $only_one;
    return $sidebars_widgets;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top