3

This question already has an answer here:

I have a sidebar which might have any number of widgets. I can count the number of widgets that exist in the sidebar. How do I display randomly only one of the widgets in my sidebar at each page load?

Use: We have specials which we display as widgets, but we only want to display one widget's content at a time in the footer of the site.

re: the count code

<?php $the_sidebars = wp_get_sidebars_widgets();
echo count( $the_sidebars['center-footer'] ); ?>

re: generating a random widget instance

<?php echo rand(1, count( $the_sidebars['center-footer'] )); ?>

marked as duplicate by Pieter Goosen, Nicolai, fuxia Jul 2 '14 at 5:30

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

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.

  • 1
    Thanx, answered. Exactly what I needed. – Gordon Jul 2 '14 at 16:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.