How to randomize the order of widgets

Sometimes you might want to display a sidebar with the widgets in a random order. It’s very simple:

add_filter ('sidebars_widgets', 'wcs_randomize_widget_order');

function wcs_randomize_widget_order($sidebars_widgets) {
    $sidebar = 'sidebar'; // Replace 'sidebar' with the name of the widget you want to shuffle
    if (isset($sidebars_widgets[$sidebar]) && !is_admin()) {
        shuffle ($sidebars_widgets[$sidebar]);
    }
    return $sidebars_widgets;
}

The check for is_admin ensures that the shuffling only occurs in the frontend.

If you want to randomize the widgets in all your sidebars, you can use:

add_filter ('sidebars_widgets', 'wcs_randomize_widget_order');

function wcs_randomize_widget_order($sidebars_widgets) {
    if (!is_admin()) {
        foreach ($sidebars_widgets as &$widget) {
            shuffle ($widget);
        }
    }
    return $sidebars_widgets;
}

Comments

  1. This is cool! I’ve wanted to randomize the order of widgets in my sidebar for a long time and didn’t think anyone had done it yet and I didn’t know where to start. I’ll dig into this and see what comes up.

Speak Your Mind

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.