Talking about Php and WordPress.
Do you need a plugin to display WordPress sidebar widgets in random order? You won’t find it. Or you will find messy scripts which need to be tweaked to return some kind of result.
That’s why I made my 22 lines script to display my sidebar widgets in random order. And not just in “random order”, because I needed to keep some widgets in fixed positions, and having the remaining ones rotating.
Motivation
Once I removed Adsense and network ads from the blog I received a lot of sponsorship requests.
There’s nothing wrong with the ones I denied, it’s just they do not match with the content of the blog.
Anyway, as I am doing some minor changes to the blog, I am starting to place the supporters in the sidebar.
Every block is a widget created from the Appearence menu this way:
And what I want is having the first and the last widgets (respectively the twitter “Follow me” button and the Facebook fan widget) to remain fixed in their first and last position, while the remaining widget should be displayed in random order.
Saying it quick, I needed a script to display in random order widgets from the i-th to the j-th
The theory
If you theme is designed according to WP guidelines, your sidebar.php file should contain something like this:
Where dynamic_sidebar
function calls each of the active widget callbacks in order, and outputs the sidebar itself.
The generated html is something like this one:
At this time, since there aren’t hooks to handle widget output, we have to save the generated html, break it into individual widgets’ html, and mix it as required.
The code
The following code shouldn’t be copied and pasted, and assumes you haven’t lists inside your widgets. But it can give you a brief idea of what you’re supposed to do.
First, call your sidebar in sidebar.php
this way:
I am calling random_widgets
function rather than dynamic_sidebar
.
The arguments are the sidebar name, the index of the first widget to be shuffled and the index of the last widget to be shuffled. Every widget outside such indexes won’t be shuffled.
random_widgets
function is defined inside functions.php
function random_widgets($sidebar,$random_start,$random_end){
ob_start();
$widgets = dynamic_sidebar($sidebar);
if($widgets){
$html = ob_get_contents();
$widgets_array = explode("
What happens? I am saving the output inside a variable called $html
. From such variable, I create an array with all widgets, break the array into sub arrays, shuffle the required array and rebuild the final code.
And that's it, without installing any plugin. You can see the result refreshing the page, sidebar widgets will shuffle, with the only exception of the first and the last widgets, which remain in their place.
Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.