Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

234 PART IV • Additional Features and Functionality


Making Widgets a Little More Dynamic
Why not just put empty widget areas where the various elements on the site could go? It will
do the job, but you’ll have to cram them in wherever they will fit, and you will have to take the
rest of the design and content into account. You will have to do that either way, of course, but
there is an alternative: Replace parts of the content with a widget area.

If you’re running a magazine-ish site, you may have an opportunity to roll out big so-called
roadblocks, ads that take over a lot more of the site than just common banners and leader-
boards. Roadblocks usually run for a shorter amount of time, and you get paid a lot for them,
compared to other ads.

Or take another approach: Say you’re an Apple blogger and you want to cover the Apple
WWDC or MacWorld in a timely manner, making sure that your readers won’t miss it. How?
Plaster the site in promotional graphics, of course!

Both of these examples will typically work poorly if you just add content into widget areas
positioned around the site’s normal elements. They will, however, work perfectly well if you
replace parts of the site’s content, meaning any element really, with a widget area. This effect is
pretty easy to get working, thanks to the fact that widget areas can come preloaded with
content.

The following code is for a widget area called Teaser, and it should come preloaded with the
content you want in that particular spot on a day-to-day basis:

<?php
if ( is_active_sidebar( 'Teaser' ) ) {
dynamic_sidebar( 'Teaser' );
} else {
/* The normal content would go here. Links, headlines, whatever... */
};
?>

Just put it in there; it can be anything, really: a headline section, a poll, must-read lists, loops,
links, images — you name it. Anything.

However, when you drop a widget in the Teaser widget area within the WordPress admin
interface, the default content won’t show; it will be replaced with the widget you dropped,
thanks to the is_active_sidebar() check. So dropping a text widget with your big fat
promo image for the Apple event, or your new e-book, or whatever, will replace the original
content. When you remove the image from the Teaser widget area, the default content will
return by default.

Pretty nifty, huh? And actually pretty simple to maintain as well; if something goes wrong,
you can just remove the widget you put there, and you’ll always revert to the default.

Another great use of widgets is navigational menus, which make sure that users can add menu
items themselves without having to rely on the theme designer.
Free download pdf