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

(avery) #1

104 PART II • Designing and Developing WordPress Themes


return $content;
}
add_filter ( 'the_content', 'Promotion' );

The function creates a variable called Promotion, which you’re storing with the HTML
code. Naturally, you could just as easily write the whole HTML in one long string, rather than
have four lines of $content, but this way makes it a bit simpler to write. Then you return
$content, which means that Promotion is now stored with the HTML you want to
output. Finally, you use add_filter to add it after the_content.

There you have it; whenever the function is called and the location is not a home page or a
feed listing (see the if clause — you may want to add more conditions there, by the way),
you’ll output the promotional box that asks the reader to subscribe to the RSS feed.

Why would you do this rather than just hack the template files? The only real reason is that
this method is pretty theme-independent, so you can just copy and paste it between your
themes and add the necessary CSS to the style sheet. Having a set of functions for the most
common content you want to output, and even hooking them on to template tags when
possible, is a way to streamline your WordPress themes even more.

As you can see, functions.php can be very handy, and it is certainly a lot more than just the
widget declarations that just about every theme has these days. That said, the widgets are the
most commonly used feature originating from functions.php, so you’ll look at those next.

UNDERSTANDING WIDGETS AND WHEN


TO USE THEM


Widgets add drag-and-drop functionality, which allows the administrator to add features to
a WordPress site from within the admin interface. This can be anything from a simple text
block in the sidebar to category listings, recent comments, or the latest updates from RSS
feeds. That is just core widget functionality built in to WordPress; add widget-ready plugins,
and you get a lot more.

When used correctly, widgets can be a great asset for a site administrator because the hands-on
way you use and alter them makes them really easy to work with. In the coming chapters,
you’ll see how you can use widget areas for tasks other than just displaying a lot of clutter in
the sidebar of typical blog 1A.

DECLARING WIDGET AREAS
It is easy to make your theme widget-ready. Do so using functions.php within your theme,
where you declare the widget areas, and then add the necessary code in your various theme
files (usually sidebar.php) where you want the widget area to show up.

The simplest way of making your theme widget-ready is just creating the default sidebar in
functions.php:

register_sidebar();
Free download pdf