How to place random widgets in the WordPress sidebar?

My pages have a sidebar with too many widgets, and it looks bad when the content is short and the sidebar is too long.

I want to randomize the widgets I’m showing in the sidebar. Meaning I will add all the potential widgets to the sidebar, and it will randomly only display a few.

I would also like some control over this, for example to have a few widgets always appear, and only the rest randomized.

I tried finding relevant plugins, but the only ones I found just randomized images or posts.. never different types of widgets.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Here comes the workaround solution discussed in the comments:

functions.php:

add_action( 'widgets_init', 'talfluxive_register_sidebars' );
function talfluxive_register_sidebars() {
    // register five random widget areas
    register_sidebars( 5, array( 'name' => 'Random Widget Area %d' ) );
    // register two fixed widget areas
    register_sidebars( 2, array( 'name' => 'Fixed Widget Area %d' ) );
}

sidebar.php

dynamic_sidebar( 'Fixed Widget Area 1' );
dynamic_sidebar( 'Random Widget Area ' . rand( 1, 5 ) );
dynamic_sidebar( 'Fixed Widget Area 2' );

This example code is very minimal and could be improved in many ways but it works and should serve as a good starting point.

PS: I really like the random widget idea. I will look for a better solution when I have more time. It’s a good plugin inspiration 🙂

Method 2

Though not completely answering your question, you could use the code presented on this page as a starting point. It’s just about randomizing the order, but with a few modifications you could make this function do exactly what you need…


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x