Editing Themes: The Key to Customizing Your Site - From Blog to Website - WordPress: The Missing Manual (2014)

WordPress: The Missing Manual (2014)

Part IV. From Blog to Website

Chapter 13. Editing Themes: The Key to Customizing Your Site

As you’ve traveled through this book, you’ve taken a look at every significant feature that WordPress offers and used those capabilities to build a variety of sites. However, you’ve always played by the rules, picking themes from the theme gallery, installing plug-ins from the plug-in directory, and sticking to the safety of the WordPress dashboard. But there’s a whole other world of possibilities for those who can color outside the lines.

The key to unlocking more flexibility and building a truly unique WordPress site is to create your own theme. As you know, a theme is a mash-up of HTML markup, formatting rules, and PHP code. Ordinarily, WordPress hides these details from you—the people who create the themes and plug-ins your site uses handle all this, while you focus on writing fab content and adjusting settings in the dashboard. But if you decide to cut loose and become a theme customizer (or even a theme creator), you step into a different world. Be forewarned: This world can seem dizzyingly complex. But you don’t need to understand every detail. Instead, you simply need to find the parts of a theme you want to change, and work on those.

In this chapter, you’ll start your journey by taking a close look at how themes work, and you’ll learn how to make small alterations that can have big effects. First, you’ll try modifying styles. Then, you’ll crack open a theme’s template files to change the code inside. All this is preparation for the next chapter, where you’ll build a new theme for a completely customized website.

The Goal: More Flexible Blogs and Sites

Before you begin fiddling with themes, you need to have a clear idea of why you’d want to do so. In other words, what do you hope to gain by changing a theme that you can’t get by using a good, preexisting theme with just the right combination of WordPress settings and plug-ins?

There are several good answers:

§ To get something exactly the way you want it

§ To make your site unique

§ To create a site that doesn’t look “bloggy” (see the next section)

Custom themes are the key to unlocking WordPress and to building any sort of website you can imagine. Your task might not be easy, but custom themes make it possible.

NOTE

Often, WordPressers first delve into a theme to make a tiny alteration. But they rarely stop there. The ability to transform a site, often by changing just a single style rule or modifying a single line of code, is addictive. If you catch the bug, you’ll want to customize every theme you touch, and you won’t be able to rest until you get exactly what you want for your site.

WordPress Sites That Aren’t Blogs

One reason to customize a theme is to create a site that looks and feels less like a blog (see the box on When Is a Blog Not a Blog?). Most WordPress sites have some characteristics that make them feel more bloggish and less like the sort of complex, traditional websites that rule the world of business and ecommerce. For example, WordPress sites usually display dated posts in reverse-chronological order. But what if you want to build a product showcase where the posts are actually product profiles, and you don’t want those profiles to include any date information at all?

Another limitation is the fact that WordPress treats all posts the same way. But what if you want to create an e-magazine with a custom-made home page for each news category you cover (Sports, Current Affairs, Lifestyle, and so on)? You can’t make those kinds of changes unless you’re willing to step away from WordPress’s blog origins and customize your theme. Do that, and you can build a WordPress site that behaves like almost any other type of site you see on the Web.

But before you get there, you need to learn a bit more about the way WordPress themes work—and lucky for you, that’s the point of this chapter. Figure 13-1 shows the final goal—a completely customized website, which you’ll learn to build in Chapter 14.

Top: Not many clues tell you that WordPress’s blogging engine powers this ecommerce store.Bottom: Here’s the same site, without a custom theme. It still functions (more or less), but it feels like a blog.

Figure 13-1. Top: Not many clues tell you that WordPress’s blogging engine powers this ecommerce store. Bottom: Here’s the same site, without a custom theme. It still functions (more or less), but it feels like a blog.

UP TO SPEED: WHEN IS A BLOG NOT A BLOG?

Originally, WordPress was designed to be the world’s best tool for building a blog. To most people, the word “blog” (short for web log) meant a personal journal made up of dated posts.

No sooner were blogs created than the definition of what a blog could do started to expand. Bloggers began creating more topical blogs—ones that provided political commentary, chronicled cooking exploits, or deconstructed popular television shows. For the most part, blogs were still intensely personal, but they were no longer restricted to people’s personal lives.

Since then, the definition of blog has continued its aggressive expansion. Today, blogs aren’t necessarily written by a single person in the first-person voice. They include sites that were never described as blogs before—for example, magazine-like news sites and picture-focused photoblogs or portfolio sites. Businesses often create “bloggy” sites rather than traditional websites, especially if they want to build social buzz or emphasize news and events. (For example, that hot restaurant setting up shop down the street might feel, legitimately so, that a blog is a better way to get people talking than a boring brochure site.)

This discussion raises an important question: When do blogs stop being blogs? Most often, you’ll recognize a blog because it contains dated entries you can read (usually) in reverse-chronological order, and browse by category or tag. However, depending on the theme you pick and the content you use, these blog-like characteristics can be deemphasized to the point where many people won’t consider your blog a blog at all. Throughout this book, you’ve seen several examples of “blogs” that stretch the definition of the word this way, such as the Canton School site (Featured Images) and the Pernatch Restaurant site (Creating a Brochure Site).

NOTE

If you’re curious to get more ideas for non-bloggish sites that WordPress can create, visit the gallery of examples at http://tinyurl.com/9dvpn3y.

Getting Ready

Before you can move from WordPress-the-blogging-platform to WordPress-the-site-design-tool, you need to satisfy a few conditions.

First, you need to have a self-hosted WordPress site. WordPress.com doesn’t give you the ability to edit themes, although it does provide a few carefully limited theme-customization features, which are outlined in the box on What About WordPress.com?. Handy as these are, they don’t measure up to the power and flexibility of self-hosted sites, where you can customize absolutely anything—as long as you’re prepared to do a little detective work to figure out what you need to change.

Second, you need to be ready to crack open the template files that run the WordPress show. To understand what’s inside, you should be familiar with the basics of HTML markup—comfortable enough to find your way through the tangle of angle brackets and elements that live in every web page. It also helps to know some CSS (that’s the Cascading Style Sheets standard that formats every modern web page). If you don’t, you’ll still be able to feel your way around with the introduction you’ll get in this chapter, but be prepared for a steep learning curve.

If your web skills aren’t quite up to snuff, here are some good resources that can help perk them up:

§ If you’ve never edited a web page before, or you need to brush up on your HTML skills, consider Creating a Website: The Missing Manual (O’Reilly) which covers HTML and CSS standards (and plenty more). Or you can read a barebones HTML tutorial at http://tinyurl.com/4mwq8.

§ To learn about CSS only, consider CSS3: The Missing Manual (O’Reilly). Or you can try an online CSS tutorial at http://tinyurl.com/mlqk7.

NOTE

You don’t need to understand everything about HTML and CSS to change a WordPress theme. You can often Google your way to the style rule or PHP code you need to implement a feature you want. You can then copy and paste that code into the right theme file, without worrying about any other details.

UP TO SPEED: WHAT ABOUT WORDPRESS.COM?

Self-hosted sites give you free rein to customize your theme, using all the techniques you’ll study in this chapter and the next. However, people with WordPress.com sites aren’t completely left out. If you buy the Custom Design upgrade (or you have a Premium account, as described on Premium Video Hosting), WordPress.com gives you a set of useful but more modest theme-editing features.

To see these features, choose Appearance→Custom Design in the dashboard menu. It’s worth noting that you can preview the features, even if you haven’t bought the Custom Design upgrade. While you won’t be able to make any changes to your site, you will be able to take a look at the options WordPress.com offers and get a sense of how much control you have over your site’s appearance.

If you plan to make straightforward changes to your site’s color scheme or fonts, the Custom Design upgrade shines. That’s because it lets you point and click your way through recommended color palettes and popular web fonts, making these types of adjustments utterly painless. But if you want to adjust other details, like the size of the sidebar or the placement of the header, you need to write your own style rules. Click CSS on the Custom Design page to get started (Figure 13-2).

With the help of the Custom Design upgrade, you can make most of the style tweaks discussed in the first part of this chapter (starting on Changing the Twenty Twelve Theme). However, you definitely won’t be able to edit template files, change the PHP code, or build a complex, custom site like the one demonstrated in Chapter 14.

Top: WordPress.com’s Custom Design upgrade lets you easily change your site’s colors and fonts and apply a new background (like the multicolored star field shown here).Bottom: Choose CSS in the righthand menu and you can make more drastic changes, but you need to know how to write a good CSS style rule and what site element to target. You’ll learn to do that starting on page 479.

Figure 13-2. Top: WordPress.com’s Custom Design upgrade lets you easily change your site’s colors and fonts and apply a new background (like the multicolored star field shown here). Bottom: Choose CSS in the righthand menu and you can make more drastic changes, but you need to know how to write a good CSS style rule and what site element to target. You’ll learn to do that starting on page 479.

Taking Control of Your Theme

Before you can create a brilliantly customized WordPress theme, you need to know a bit more about how themes work behind the scenes.

When you first met themes in Chapter 5, you discovered that every theme consists of a combination of files. These files work together to create all the pages on your WordPress site, and they fall into three basic categories:

§ Style sheets. These files contain style rules that format different parts of your site, such as headlines, sidebar headings, and links. They use the much-loved CSS standard, which will be familiar to anyone who’s dabbled in web design.

§ Templates. These files contain a mix of ordinary HTML and PHP code. Each template is responsible for a different part of your site—for example, there’s a template for the list of recent posts, the page header, the footer, the single-post view, and so on.

§ Resources. These are other files that your theme’s templates might use, often to add a bit of pizzazz. Examples include image files, like the one Greyzed used to create its dirty stone background (Choosing a New Theme), and JavaScript code, like the stuff the Brightpage theme used to run its featured image slideshow (Featured Images).

At a bare minimum, every theme needs two files: a single style sheet named style.css, which sets the colors, layout, and fonts for your entire site, and a template named index.php, which creates the list of posts on your home page. Most themes have a few more style sheets and many more templates, but you’ll get to that in a moment.

How WordPress Stores Themes

On your WordPress site, the wp-content/themes folder holds all your themes. For example, if your website address is http://magicteahouse.net, the Twenty Twelve theme will be in the following folder:

http://magicteahouse.net/wp-content/themes/twentytwelve

Each theme you install gets its own subfolder. So if you install seven themes on your website, you’ll see seven subfolders in the wp-content/themes folder, even though you use only one theme at a time.

All of a theme’s style sheets and template files reside inside the theme’s folder (Figure 13-3). Most themes also have subfolders. For example, they might tuck JavaScript files into a subfolder named js and image files into a subfolder named images. You don’t need to worry about these details as long as you remember that themes are a package of files and subfolders you need to keep together in order for your site to function properly.

Here’s a look inside the Twenty Twelve theme folder on your web server, opened in Windows Explorer through an FTP connection. If you’re handy with an FTP program, you can add and remove theme folders without firing up WordPress’s dashboard.

Figure 13-3. Here’s a look inside the Twenty Twelve theme folder on your web server, opened in Windows Explorer through an FTP connection. If you’re handy with an FTP program, you can add and remove theme folders without firing up WordPress’s dashboard.

Style.css: How a Theme Identifies Itself

The style.css file is the starting point for every theme. In most themes, it’s a huge file packed with formatting instructions. For example, the Twenty Twelve theme’s style.css file weighs in with nearly 2,000 lines of formatting magic.

The style.css file defines a few essential pieces of information about the style itself, using a theme header at the beginning of the file. Here’s a slightly shortened version of the header that starts the Twenty Twelve style.css file. Each distinct bit of information is highlighted in bold:

/*

Theme Name: Twenty Twelve

Theme URI: http://wordpress.org/themes/twentytwelve

Author: the WordPress team

Author URI: http://wordpress.org/

Description: The 2012 theme for WordPress is a fully responsive the

me ...

Version: 1.3

License: GNU General Public License v2 or later

License URI: http://www.gnu.org/licenses/gpl-2.0.html

Tags: light, gray, white, one-column, two-columns, right-sidebar, f

luid-lay-

out,

...

*/

WordPress brackets the header with two special character sequences: It starts with /* and ends with */, the CSS comment markers. As a result, browsers don’t pay any attention to the header. But WordPress checks it and extracts the key details. It uses this information for the theme description you see in the Add Themes page (Installing a Theme on a Self-Hosted Site). It also tracks the version number and checks the theme URL for new versions. (Although it says “URI” in the theme file, a URI is the same as a URL when you deal with content on the Web, as in the case of themes.)

If your theme lacks these details, WordPress won’t recognize that it’s a theme. It won’t show it in the Appearance→Themes section of the dashboard, and it won’t let you activate it on your site.

NOTE

Many themes include style sheets beyond style.css. However, these style sheets add extra features or handle special cases—for example, they provide alternate color schemes, deal with old browsers, handle languages that write text from right to left, and format the content in the editing box on the Add New Post page so that it provides the most realistic preview possible.

The Theme Editor

To edit a theme, choose Appearance→Editor in the dashboard. This takes you to the Edit Themes page, with your theme’s main style sheet, styles.css, open (Figure 13-4).

When you visit the Edit Themes page, WordPress automatically opens and displays your theme’s style.css file because it’s the one people edit most often. But you can peek at any other theme file by clicking the corresponding link on the right. Templates appear first in the list, followed by style sheets (not shown here). The editor doesn’t display a theme’s resource files.

Figure 13-4. When you visit the Edit Themes page, WordPress automatically opens and displays your theme’s style.css file because it’s the one people edit most often. But you can peek at any other theme file by clicking the corresponding link on the right. Templates appear first in the list, followed by style sheets (not shown here). The editor doesn’t display a theme’s resource files.

WordPress splits the Edit Themes page into two parts. On the left is a giant text box where you edit your theme, one file at a time. On the right is a sidebar that lists all the files in your theme.

Once you finish editing a file in your theme, click Update File to save your changes. You can then choose a different file to edit.

If you want to make extensive changes to a theme, you might not want to do all the work in the cramped environment of the dashboard. You might prefer to download your theme files and edit them offline, using a more powerful program. Some web editing programs, like Dreamweaver, even have built-in theme-editing features for WordPress.

One way to do this is to pick the file you want to edit, copy its content, and paste it into a text editor (like Notepad on Windows PCs or TextEdit on Macs). Then, after you make your changes, copy the edited content back into the editing box on the Edit Themes page. But if you’re going to edit multiple files, it’s easier to download the whole theme folder. To do that, browse to your website with an FTP program (as shown in Figure 13-3) and then drag the theme folder to your computer’s desktop. When you finish making changes, delete the original folder from your website and then upload the updated folder from your desktop computer to your site.

WARNING

The theme editor can be an unforgiving tool. WordPress does not store past versions of your theme files, so once you save an edit, there’s no way to restore your site to its previous state. (You can reapply the original theme from the Themes page, but that wipes out all your theme-editing changes.) To make sure you don’t run into trouble, get into the habit of making basic, bare-minimum backups. Before you make a big change to a theme file, copy all the content from the editing box in the Edit Themes page, and paste it into a blank text file on your computer.

Protecting Yourself with a Child Theme

Before you start mucking around with one of your themes, you should think about the long-term effects. Someday, probably not long from today, the person who created the theme you’re editing will release a new and improved version that you’ll want to use on your site. Here’s the problem: If you install a theme update, you wipe out all the edits you made to your theme files. Editing themes is enough work without having to do it over and over again.

Fortunately, there’s a solution. You can create a child theme, which takes the current theme as a starting point and lets you slap your customizations on top of it. You don’t change the original theme (known as the parent theme) at all. Instead, you selectively edit the templates and style sheets and save those altered files in the child theme folder. These new files override the same-named templates and style sheets in the parent theme, so you get the features you want in your site. And when you update the parent theme at some future date, your customizations stay in place, because WordPress stores the child theme as a separate group of files.

When you customize a theme, you should always start by creating a child theme. It’s the safest approach, and the only way to guarantee that your work will survive future changes.

However, if you want to create a completely new theme (rather than customize an existing one), you need a different approach. You might still use an existing theme as a starting point for your work, but there’s no need to create a child theme. Your changes will be so significant that future updates and fixes won’t be relevant to your tricked-out theme.

All the examples in this chapter use child themes. Creating a complete theme on your own is a significant undertaking for even the best propeller heads among us, although you’ll get an introduction to the practice in Chapter 14.

Creating a Child Theme

To create a child theme, start by adding a new theme folder in the wp-content/themes section of your website. Name the folder whatever you want. However, unlike a normal theme folder, you don’t need to fill this folder with files. All you need to do is put a new style.css file inside the folder—one that links itself to the parent theme via the theme header.

If this sounds like a slightly intimidating challenge, don’t worry. Rather than go through the hassle of creating the folder for your child theme and creating the style.css file with the right header, you can use a tiny plug-in, called One-Click Child Theme (http://tinyurl.com/child-theme), to help you out. Here’s what to do:

1. Install and activate the One-Click Child Theme plug-in.

Choose Plugins→Add New, and search for it by name.

TIP

WordPress has several similar plug-ins that can help you create child themes. To see them all (and possibly choose a different one), search the plug-in repository for “child theme.”

2. Activate the theme you want to customize.

The One-Click Child Theme plug-in assumes you want to create a child theme for the currently active theme on your site. If that’s not the case, go to Appearance→Themes and activate the right theme before you continue.

3. Choose AppearanceChild Theme.

This is a new menu command, courtesy of the One-Click Child Theme plug-in. It opens the Create a Child Theme page (Figure 13-5).

You need to provide only a few pieces of information to create a child theme. Here, you’re about to create a child theme named “Twenty Twelve Reboot.”

Figure 13-5. You need to provide only a few pieces of information to create a child theme. Here, you’re about to create a child theme named “Twenty Twelve Reboot.”

NOTE

To follow along with the examples in this chapter, use the Twenty Twelve theme. It’s a good starting point for theme-customization practice because it’s clean, straightforward, and adaptable. If you decide to start with a different theme, all the concepts described in this chapter still apply, but the exact class names and formatting details will vary.

4. Supply a name for the theme, a brief description, and your name.

The One-Click Child Theme plug-in puts these details in the header of the style.css file. It uses your name as the theme’s author.

5. Click Create Child.

The One-Click Child Theme plug-in creates the child theme folder on your web server and creates a new style.css file inside it. It then activates the child theme on your site.

In this example, the theme is named Twenty Twelve Reboot, so the newly created folder will be named twenty-twelve-reboot.

6. To verify that your child theme is working, choose AppearanceThemes.

You’ll see your new child theme at the top of the page (Figure 13-6).

Right now, the Twenty Twelve Reboot child theme is identical to its parent theme, Twenty Twelve. The One-Click Child Theme Plug-In even gives it the same thumbnail picture.

Figure 13-6. Right now, the Twenty Twelve Reboot child theme is identical to its parent theme, Twenty Twelve. The One-Click Child Theme Plug-In even gives it the same thumbnail picture.

7. Optionally, deactivate the One-Click Child Theme plug-in.

Unless you plan to create another new child theme, you don’t need to keep One-Click Child Theme active. Head to the plug-in page (click Plugins) and use the Deactivate link to switch it off.

How Child Themes Work

If you check out the newly created folder for your child theme, you’ll find that it holds just three files. The first is the all-important style.css. The second is a supplementary style sheet for right-to-left languages, named rtl.css. The third is an image named screenshot.png that WordPress copied from the parent theme; it uses that image as the thumbnail on the Themes page (Figure 13-6).

To start editing your child theme, choose Appearance→Editor. Start with the style.css file (Figure 13-7), as you do when you edit a normal theme.

A child theme starts life as little more than a stripped-down style.css file that refers back to its parent theme. As you edit the child theme, you’ll need to visit the parent theme frequently (click the link shown here) because it’s the starting point for many of your changes.

Figure 13-7. A child theme starts life as little more than a stripped-down style.css file that refers back to its parent theme. As you edit the child theme, you’ll need to visit the parent theme frequently (click the link shown here) because it’s the starting point for many of your changes.

The key to a child theme is its style.css style sheet. Unlike the style.css file in the parent theme, style.css in the child theme contains just a few lines of text. Here’s the complete style.css file in the Twenty Twelve Reboot theme:

/*

Theme Name: Twenty Twelve Reboot

Description: This is a customized version of the Twenty Twelve Theme for the

Magic Tea House.

Author: Katya Greenview

Template: twentytwelve

*/

@import url("../twentytwelve/style.css");

You’ve already seen the first three details (theme name, description, and author). However, the template setting is new—it points to the parent theme’s folder. When WordPress sees this setting, it knows to look in a folder named twentytwelve (in the themes section of your site). When it does, it finds the files for the familiar Twenty Twelve theme.

Unlike the original version of the style.css file in the Twenty Twelve theme, the child theme contains just a single line after the header. This line grabs all the styles from the Twenty Twelve theme and applies them to the child theme:

@import url("../twentytwelve/style.css");

If you’re foolish enough to delete this line, your site will lose all the styles from the parent theme. (You can try it out; just remember to add the @import statement back when you finish.) Suddenly, all your text will switch to the generic Times New Roman font, your nicely formatted headings will disappear, and the layout of your headers, footers, and sidebar will get scrambled together in a mess.

TIP

Child themes are a great way to customize your site permanently, but they’re also a handy tool for temporarily changing your formatting. For example, if you’re running the Magic Tea House site, you might decide to hold a special winter promotion. During this promotion, you plan to make sweeping changes to your site’s color scheme. If you use a child theme to redecorate, you can quickly go back to your original theme when the promotion ends—just choose Appearance→Themes and activate the parent theme.

GEM IN THE ROUGH: ADDING STYLES WITH JETPACK: ANOTHER APPROACH

A child theme is the tried-and-true method for safely customizing a theme, but if you use Jetpack—the handy plug-in that aims to give self-hosters the features of WordPress.com—you have another option.

Recent versions of Jetpack include a CSS-editing feature that acts like the Custom Design upgrade in WordPress.com. Its chief advantage is that it lets you add to your site’s style rules without modifying your theme’s style sheet, so there’s no need to create a child theme. But this simplicity comes at a price: It limits your power and flexibility. Although this feature is good enough for the style refinements you’ll see in the next section, it doesn’t let you safely edit templates—a key feature you’ll tap in the latter half of this chapter and in Chapter 14.

To use Jetpack’s CSS editing feature, choose Appearance→Edit CSS. You’ll see an editing box that looks strikingly similar to the one you use when editing a style sheet in a child theme. As with a child theme, the style rules you add here override those in your original theme. Unlike a child theme, you won’t see the @import statement, because Jetpack automatically merges the original styles with your customizations.

When you add custom styles with Jetpack, your styles aren’t stored in a file; they’re stored in your site’s database. This can cause a few quirks—for example, you lose the styles you edited if you disable Jetpack (remember to copy your custom styles from the editor and paste them into a text file first). And every time you switch themes, Jetpack wipes the slate clean and deletes your custom styles. However, Jetpack also includes a handy revision tracker that works just like the post revision system (Editing a Gallery), and “remembers” your 25 most recent theme revisions. If you make a big editing mistake, or if you switch themes and want to get your old work back, click the revision you want in the CSS Revisions box.

Overall, Jetpack is a worthy tool for minor theme changes if you already use the plug-in. But if you’re more ambitious and you might be editing a template or two in the future, a child theme is the only way to go.

Editing the Styles in Your Theme

There are a number of reasons you might crack open your theme’s styles and make changes:

§ Unique-ify your theme. You might change your theme to make sure your site doesn’t have the same look as other sites that share that theme. After all, there are only so many themes, and if you pick a good one, it’s a safe bet that you’re following in the footsteps of thousands of other webmasters.

§ Branding. Perhaps you need your theme to match the official corporate colors of your business. Or you might want it to more closely resemble another website, run by the same business, that doesn’t use WordPress.

§ Highlight certain design elements. By changing a theme, you can emphasize details that are important to you. For example, you may want to use a style that makes author comments stand out (Step 2. Examine the Template File).

To make changes to any theme, you follow two steps. First, you create a child theme (Protecting Yourself with a Child Theme), and then you add one or more style rules to the style.css file in that theme. These rules selectively override the original theme, letting you change whatever you don’t like. Some of the details you alter include colors, fonts, spacing, and borders. You can also hide design elements you don’t want to see.

However, making these changes isn’t quite as easy as it sounds. To cook up the right style rule, you need to know a bit more about the CSS standard and the styles your theme uses. Every theme is slightly different, but most include a gargantuan style.css file stuffed full of formatting instructions. Finding the exact detail you want to override may take some digging. In the next section, you’ll take your first look at the sort of instructions the style.css file contains.

NOTE

If you’re already well versed in the CSS standard, you can skip the next section and continue on to the one after that, Changing the Twenty Twelve Theme.

Taking a Look at the Style Rules in Your Theme

Reading the average style.css file is not for the faint of heart. As explained earlier, the typical theme includes hundreds or thousands of formatting instructions. Understanding any one of them isn’t too difficult, but finding the exact one you want can be a challenge.

FREQUENTLY ASKED QUESTION: FIND YOUR STYLE SHEET IN WORDPRESS.COM

I bought the Custom Design upgrade so I can add my own styles, but where can I find the rules from the original style sheet?

To create your own styles, you need to understand the styles that are already at work on your site. Unfortunately, WordPress.com hides your theme’s style sheet, even after you buy the Custom Design upgrade. Why? In the past, when this style sheet was more visible, WordPress.com users kept making the same mistake: They’d copy the whole thing into the CSS editor and then make their changes. (Of course you know better, and you’ll only put changed styles into the CSS editor.)

So how do you find your site’s style sheet, so you can study it and figure out what you want to change? It’s a bit tricky, but here’s how to dig it up:

1. Click Appearance→Custom Design. Then click CSS. This takes you to the CSS editor where you enter your custom styles.

2. Click CSS Revisions, just above the post editor. This shows the CSS editor with your customized CSS file, as before, but now with more options.

3. In the Publish box, next to the Mode option, click Edit. You’ll see two options that control how WordPress.com uses your styles.

4. Look at the “Replace theme’s CSS” option, but don’t turn it on. (In fact, there’s almost never a good reason to use this setting.) Instead, notice how part of the option—the words “theme’s CSS”—is a link. Click that link, and you see the full style sheet for your theme, nicely formatted so you can read it in your browser.

Decoding a Basic Style Rule

The first step to understanding CSS styles is to take a look at a few rules and get familiar with their syntax.

Every style sheet is a long list of rules, and every rule follows the same format, which looks like this:

selector {

property: value;

property: value;

}

Here’s what each part means:

§ The selector identifies the type of content you want to format. A browser hunts down all the elements on a web page that match that selector. There are many ways to write a selector, but one of the simplest (shown next) is to identify the elements you want to format by their element name. For example, you could write a selector that picks out all the level-1 headings on a page.

§ The property identifies the type of formatting you want to apply. Here’s where you choose whether you want to change colors, fonts, alignment, or something else. You can have as many property settings as you want in a rule—the example above has two.

§ The value sets a value for the property. For example, if your property is color, the value could be light blue or queasy green.

Now here’s a sample rule, of the sort you’ll find in a theme like Twenty Twelve:

body {

background: #fff;

line-height: 1;

}

This tells a browser to find the web page’s <body> element, which wraps all the content on the page. The browser applies two formatting instructions to the element. First, it changes the background color. (You’ll be excused for not knowing that #fff is an HTML color code that means white.) Second, it sets the line spacing to a normal value of 1. (A higher value would add more space between each line of text.)

You need several skills to decode a style rule like this. First, you need to know the basics of HTML, so you can understand what the <body> element is and what it does in a web page. Second, you need to know what style properties are available for you to tweak. Style rules let you change color, typeface, borders, size, positioning, and alignment. To understand the sample rule shown above, you need to know that CSS defines a background property that lets you change the color behind an element. Third, you need to know what values are appropriate for a property—for example, you set a page’s background color using an HTML color code. (In the case of colors, you can pick the color you want and get its HTML color code from a color-picking site like www.colorpicker.com.)

TIP

You can get style sheet help from a book like CSS3: The Missing Manual (O’Reilly). Or, if all you need is an overview of the style properties you can change and their acceptable values, check out the style sheet reference at http://tinyurl.com/bz5tcp.

Multiple Rules and Media Queries

Sometimes, a style sheet contains multiple rules for the same element. In such a situation, the browser combines all the property settings into one super-rule. For example, you can break the style sheet rule you just saw into two pieces, like this:

body {

background: #e6e6e6;

}

body {

line-height: 1;

}

In this case, the effect is the same. Big style sheets may use this approach to break down complex rules and better organize them.

Some style sheets include media queries—one or more blocks of conditional rules that spring into action when certain browser conditions are met. You can recognize a media query by the fact that it starts with the code @media. Here’s an example:

@media screen and (min-width: 960px) {

/* Conditional styles go in here.

}

This translates into the following instruction: “If this page is currently being displayed on a screen (not sent to a printer or some other device), and the width of the page is at least 960 pixels, then run the following styles.” Older themes don’t use media queries, but mobile-aware themes rely on this technique to change your layout for different devices, like smartphones (Mobile Themes).

All the WordPress year themes, from Twenty Twelve on, use media queries. In fact, if you dig through the Twenty Twelve style sheet, you’ll find no fewer than three style rules that target the <body> element—two that are always in effect, and one that conditionally changes the background color from white to gray:

@media screen and (min-width: 960px) {

body {

background-color: #e6e6e6;

}

}

If you wonder why Twenty Twelve uses this color-changing trick, visit a site that uses the theme and shrink your browser window. In a wide window, the conditional rule applies a gray outline around the content (which always appears on a white background). But if you shrink the window, that gray edge disappears.

Class and ID Selectors

The style sheet rules above target the <body> element. This type of rule is called an element rule, because it applies to a specific element on a page. For example, if you write a rule that formats <h1> headings, every first-level heading on the page gets the same formatting.

CSS supports other types of selectors, and WordPress themes use them heavily. One of the most popular is the class selector, which starts with a period, like this:

.entry-header {

margin-bottom: 24px;

}

This rule formats any element that has a class named entry-header applied to it. If you look at the HTML markup for one of your posts, you’ll find an element tagged with the entry-header class, like this:

<header class="entry-header">

<h1 class="entry-title">Magic Tea House's Grand New Opening</h1>

<div class="comments-link">

<a href="http://magicteahouse.net/grand-new-opening/#respond"

title="Comment on Magic Tea House's Grand New Opening">

<span class="leave-reply">Leave a reply</span>

</a>

</div>

</header>

Here, the theme uses the entry-header class to wrap the header section of each post, which includes the post title and the “Leave a reply” comments link.

It’s important to realize that the word “entry-header” doesn’t mean anything special to WordPress or to a browser. It’s simply a naming convention the Twenty Twelve theme uses (as do many other themes).

NOTE

Sometimes, you’ll see a CSS rule that combines element selectors and class selectors. So the selector h1.entry-title refers to any level-1 heading that uses the entry-title class.

There’s one more selector that’s similar to class selectors, called an ID selector. It starts with a # character. Here’s an example that uses an ID named colophon:

#colophon {

}

NOTE

In Twenty Twelve, a colophon is the footer at the very bottom of each page of your site. Ordinarily, it contains the text “Proudly powered by WordPress.”

Here’s the snippet of HTML that gets its formatting from this rule:

<footer id="colophon" role="contentinfo">

<div class="site-info">

<a href="http://wordpress.org/"

title="Semantic Personal Publishing Platform">

Proudly powered by WordPress</a>

</div>

</footer>

The difference between class selectors and ID selectors is that a class selector can format a number of elements (provided they all have the same class applied to them), while an ID selector targets just a single HTML element (because two elements can’t have the same ID). A WordPress page will have only one colophon, so it makes sense to use an ID selector for it, even though a class selector would work just as well.

NOTE

Some style sheets use ID selectors heavily, while others do all their work with class selectors. It’s really a matter of preference. You simply need to follow the convention your theme uses.

This is where things can get a bit head-spinny. Understanding the syntax of CSS is one thing, but editing the styles in a theme means knowing which class and ID names that theme uses, and what elements are associated with those names. You’ll get some pointers on Puzzling Out the Styles in a Theme.

Combining Selectors

You can combine selectors to create even more powerful formatting rules, so long as you separate them with a comma. WordPress then applies the style rule to any element that matches any one of the selectors.

Here’s an example that changes the alignment of three HTML elements—the <caption> element used with figures and the <th> and <td> elements used with tables.

caption, th, td {

text-align: left;

}

You can also create more complex rules that match elements inside other elements. This is called a contextual selector, and you build one by combining two ordinary selectors, separated by a space. Here’s an example:

.comment-content h1 {

...

}

This selector matches every <h1> element inside the element with the class name comment-content. It formats the heading of every comment, while ignoring the <h1> elements that appear elsewhere on the page.

WordPress loves contextual selectors—in fact, most of the Twenty Twelve theme’s style rules use contextual selectors. If you haven’t seen them before, they may take some time to decipher. Just remember that a browser works on the selectors one at a time. It starts by finding an element that matches the first selector, and then it looks inside that element to match the second selector (and if the rule includes another selector, the browser searches inside that element, too).

Here’s another example to practice your CSS-decoding skills:

.entry-header .entry-title {

font-size: 20px;

line-height: 1.2;

}

Got it? This selector looks for an element with the class name .entry-title inside an element with the class name .entry-header. The end result is a rule that targets the title in the post header. The creators of the Twenty Twelve theme could have written a simplified rule that applies to the entry-title class, no matter where it appears, but they chose to be more specific.

Sometimes there are good reasons for being more specific and writing contextual selectors. For example, the creators of Twenty Twelve might want to show the post title in different places, without using the same formatting. In other cases, theme designers use a contextual selector to indicate the relationship of classes and the structure of the site. (For example, the .entry-header .entry-title rule tells you that this theme puts entry titles inside an entry header.) To you, it shouldn’t matter. In most cases, when you want to modify your theme’s CSS, you find the style rule that controls the detail you want to change and you copy the selector exactly.

UP TO SPEED: PIXELS AND REMS: TWO WAYS TO MEASURE THE SAME THING

The style sheet rules you see in this chapter are slightly simplified from the versions you’ll find in the Twenty Twelve theme. Oddly enough, Twenty Twelve sets dimensions twice, using two different units of measure. First, it uses pixels, and then it sets the same amount of margin space using a curious unit called rems:

font-size: 20px;

font-size: 1.25rem;

Browsers that understand rems pay attention to the second line. Browsers that don’t (old versions of Internet Explorer) use the first line. Either way, the result is equivalent and the element looks the same in the page.

Of course, this practice raises two clear questions: What’s the difference between a pixel and a rem, and why would you prefer one over the other? The short answer is that it’s a historical quirk fuelled by browser behaviors of the past. Today, the choice between pixels and rems is really a matter of personal preference. But if you want to know the nitty-gritty, keep reading.

The most obvious difference between the two units of measure is that the scale is different. A single rem adds up to 14 pixels, which is the type size of normal text. So if you set a width of 300 pixels, you’d use 21.43 rems to match. Beyond that, the situation gets murky. In the recent past, rems were special because they were a relative unit of measurement. Web pages that used them could scale themselves to suit a browser’s text size setting, satisfying visually impaired people and fitting into the small screens of mobile devices. By comparison, pixels were bad, because they trapped pages in fixed layouts that couldn’t adapt to different situations. Today, these problems are resolved, and browsers can scale pages that use pixel sizes in much the same way they scale pages that use rems. In fact, the year themes that came after Twenty Twelve, like Twenty Fourteen, have switched back to using pixels only.

Changing the Twenty Twelve Theme

The Twenty Twelve theme is filled with styles, and you can override any of them. For example, say you decide that you don’t want the standard menu bar to appear on your site. The menu isn’t a widget; it’s a built-in part of the Twenty Twelve theme. But here’s where your child theme and CSS knowledge pay off, because you can hide the menu by using the right style rule.

To do that, choose Appearance→Editor to start editing the style.css file in your child theme (Figure 13-8). Then add this rule:

.main-navigation {

display: none;

}

This works because the .main-navigation class is attached to a <nav> element that holds the menu for your site. The display: none instruction tells browsers to collapse this element, and its contents, into nothingness.

NOTE

When you add a style rule to a child theme, it overrides any conflicting rule in the parent theme, but it allows style settings that don’t conflict. For example, if you change the color of your post title in the child theme, that won’t affect the font the parent theme applies to the title.

Here’s the style.css file from Twenty Twelve Reboot, the Twenty Twelve child theme. The style rules you place here override the parent theme’s formatting instructions for same-named classes and IDs. Right now, Reboot adds just a single style rule (circled).

Figure 13-8. Here’s the style.css file from Twenty Twelve Reboot, the Twenty Twelve child theme. The style rules you place here override the parent theme’s formatting instructions for same-named classes and IDs. Right now, Reboot adds just a single style rule (circled).

If you’re comfortable with CSS (or you’re using one of the CSS resources mentioned on Getting Ready), you’ll have no trouble understanding the display property. However, you might have more trouble finding the ID and class names of the elements you want to change. Table 13-1provides a cheat sheet to some of the key elements in the Twenty Twelve theme.

Table 13-1. Class Names in the Twenty Twelve Theme

STYLE SELECTOR

CORRESPONDS TO…

.site-header

The header section at the top of every page; it includes the site title, site description, navigation menu, and header image.

.site-header img

Just the header image. Use this class to change the header’s size or position.

.site-title

The site title in the header (for example, “Magic Tea House”).

.site-description

The byline that appears under the site title in the header (for example, “Tea Emporium and Small Concert Venue”).

.site

All the content in the page, including the header and footer. The style for this class sets the maximum width of the site layout (currently, that’s 960 pixels).

.widget-area

The right sidebar that holds all the widgets. The style for this class allocates 26 percent of the available width to the sidebar, and the content area gets the remaining space.

.front-widgets

The bottom sidebar on the front page, when you use the Front Page template (Better Home Pages).

.widget

Any widget in a widget area.

.widget-title

The optional title that appears above a widget.

.nav-menu

The navigation menu at the top of each page.

.nav-menu li

An individual entry in the navigation menu.

.colophon

The footer area on every page, starting with the solid horizontal line that separates the footer from the main content area.

.entry-title

The title of any post. Post titles appear in several places (including the home page, the single-post page, and the search page). You probably don’t want to format titles all the same way, so you need to combine a class name with another selector, as shown in the next three examples.

.blog .entry-title

The title of any post in the main list of posts.

.single .entry-title

The title of any post on a single-post page.

.template-front-page .entry-title

The title of any post on a showcase page.

.entry-content

The content in the post. As with the entry-title class, this applies to the post content no matter where it appears, unless you combine this selector with another one.

.entry-meta

The information about the post, which appears before it (for example, “Posted on January 14, 2014” and after it (“This entry was posted in News by Katya Greenview on March 16, 2014.”)

.comments-area

The comments area after a post.

.comment-meta

The byline for a comment, such as “Salah on April 26, 2014 at 11:00 pm said:”

.comment-content

The comment text, after the byline.

.commentlist li.bypostauthor

A comment left by you (the author of the post).

.commentlist li.byuser

A comment left by someone other than you.

.logged-in

A class added if the current visitor is logged in as a website user (Adding People to Your Site). For example, you can use the selector .logged-in body to change the formatting of the <body> element for people you know.

Although Table 13-1 is tailored to the Twenty Twelve theme, many other WordPress themes follow a similar structure. The standard year themes (such as Twenty Thirteen and Twenty Fourteen) are particularly consistent. And WordPress itself is responsible for adding class names like .blog,.single, and .logged-in to the <body> element to flag key details about the current state of a page. However, other themes are free to change many of these details in ways both subtle and maddening. For most class names, there are no guarantees, so every theme customization task must begin with a process of exploration.

Once you get the right class or ID name, you can target the exact visual ingredient you want to alter. For example, to change the font, color, and size of the text in a blog post in a single-post page, you can add a style rule like this:

.entry-content {

font-family: "Times New Roman";

color: red;

font-size: 21px;

}

Type it into the editor (Appearance→Editor), hit Update File, and refresh the website to see the change (Figure 13-9).

Top: The ordinary face of Twenty Twelve.Bottom: This revamped post, with its large red-lettered text, doesn’t exactly look better, but it does look different.

Figure 13-9. Top: The ordinary face of Twenty Twelve. Bottom: This revamped post, with its large red-lettered text, doesn’t exactly look better, but it does look different.

It’s a simple recipe: Find the class name or ID name for the element you want change, add some style properties, and your page gets an instant makeover.

Here’s another example that makes your comments ridiculously obvious, with a yellow background, bold text, and a gray border:

.commentlist li.bypostauthor {

background-color: LightYellow;

font-weight: bold;

border: 1px solid gray;

}

In this case, it isn’t enough to just use the .bypostauthor selector on its own. That’s because the style.css file in the original Twenty Twelve theme uses a more specific version of .bypostauthor. CSS won’t allow a more general selector (like .bypostauthor) to override a more specific one (like.commentlist li.bypostauthor) if their properties conflict. For that reason, you need to use the longer selector .commentlist li.bypostauthor in your child theme if you want the theme to apply your new rule.

Puzzling Out the Styles in a Theme

Half the battle in editing style.css is figuring out how to write your selector. Often, you won’t know the class or ID name of the page element you want to change, so you need to do a bit of detective work.

The best starting point is to scour the HTML that WordPress creates for your page. You can do this in any browser by visiting the page, right-clicking it, and choosing a command with a name like “View Source.” This shows you the complete HTML markup, and you need to search for the piece of content you want to change. To get started, hit Ctrl+F (Command+F on Macs), and type in a bit of the text that’s near the part of the page you want to change. For example, to change the comments section, you might search for “Leave a Reply” to jump to the heading that starts off the section. Many browsers make this process easier with a feature for homing in on the HTML in a specific part of a page (Figure 13-10).

Once you find the right place—roughly—the real hunt begins. Look at the elements just before your content, and check the class and id attributes for names you recognize, or that seem obvious. Pay special attention to the <div> element, which HTML pages use to group blocks of content, like sidebars, posts, menus, headers, and footers. You’ll often find one <div> nested inside another, which lets the theme apply a layered tapestry of style settings (which is great for flexibility, but not so good when you’re trying to understand exactly what rule is responsible for a specific formatting detail).

In the Firefox and Google Chrome browsers, there’s an easy way to find the class name of an element without searching through all the HTML on a page. Just right-click the part of the page you want to examine and choose “Inspect element.” A panel opens with the corresponding bit of HTML markup selected. That quickly tells you that the post title is an <h1> element with the class name entry-title (but you already knew that). In Internet Explorer, you need to first press F12 to open the Developer Tools panel. Then choose Find→“Select element by click” at the top of the panel and click the part of the page you want to examine.

Figure 13-10. In the Firefox and Google Chrome browsers, there’s an easy way to find the class name of an element without searching through all the HTML on a page. Just right-click the part of the page you want to examine and choose “Inspect element.” A panel opens with the corresponding bit of HTML markup selected. That quickly tells you that the post title is an <h1> element with the class name entry-title (but you already knew that). In Internet Explorer, you need to first press F12 to open the Developer Tools panel. Then choose Find→“Select element by click” at the top of the panel and click the part of the page you want to examine.

TIP

WordPress.com has a few helpful videos that show how to pinpoint individual elements in a web page, using different web browsers. You can watch these micro-overviews at http://tinyurl.com/css-inspection.

Once you have a potential class or ID name, it’s time to experiment. Pop open the theme editor and add a new style rule that targets the section you identified. Do something obvious first, like changing the background color with the background-color property. That way, you can check your site and immediately determine if you found the right element.

Using Fancy Fonts

One of the most common reasons to edit the styles in a template is to change an element’s font. In fact, it’s often the case that all you need to do to turn a popular theme into something uniquely yours is to change some of the typefaces.

Originally, HTML pages were limited to a set of web-safe fonts. These are the typefaces every web surfer has seen, including stalwarts like Times New Roman, Arial, and Verdana. But web design has taken great strides forward in recent years with a CSS feature called embedded fonts. Essentially, embedded fonts let you use almost any typeface you want on your web pages—you just need to upload the font to your web server in the right format.

The embedded fonts feature has a few quirks. First, it doesn’t work with older browsers, so you need to make sure your pages look respectable even if your visitor’s browser can’t load the embedded fonts. Second, although every modern browser supports embedded fonts, they don’t all understand the same font files. For that reason, web designers often have to upload several copies of the fonts they want to use, each one in a different format. And, third, the CSS rule you write to use embedded fonts is a bit convoluted, which can make for a few unnecessary headaches.

Happily, you can sidestep all these problems by using a web font service like Google Web Fonts. There, you can pick from a huge gallery of attractive typefaces. When you find a font you want, Google spits out the CSS style rule for you. Best of all, Google hosts the font files on its high-powered web servers, in all the required formats, so you don’t need to upload anything to your site.

TIP

If you want to learn everything there is to know about web fonts, including how to host them on your website, write the CSS rules yourself, and web-ify your own fonts, check out HTML5: The Missing Manual (O’Reilly), which has a section all about embedded fonts.

To use a Google font on a WordPress site, follow these steps:

1. Go to www.google.com/fonts.

Google displays a long list of fonts (Figure 13-11). At the time of this writing, there were well over 500 typefaces to choose from.

2. When you see a font you like, click the “Pop out” button to take a closer look.

Google opens a font preview page that shows the font at different sizes.

To find just the right typeface for your site, you can sort and filter Google’s font list. For example, you can see the most popular fonts first, and you can filter for just serif, sans-serif, or handwritten (cursive) fonts.

Figure 13-11. To find just the right typeface for your site, you can sort and filter Google’s font list. For example, you can see the most popular fonts first, and you can filter for just serif, sans-serif, or handwritten (cursive) fonts.

3. If you like the font, click the “Quick use” button.

Google shows you a page with information on how to use the font. It consists of a style sheet link (which you must add to your web page) and an example of a style sheet rule that uses the font.

TIP

Google also lets you choose your favorite fonts from its site and put them in a personalized collection. If you do, Google gives you a few added features, like the ability to download a copy of the font to install on your computer for print work. Google also remembers the fonts you store in your collection when you return to the Google Web Fonts site.

4. Scroll down the page until you find the blue set of tabs with the caption “Add this code your website” (Figure 13-12). Click the @import tab.

Google has created a ready-made style sheet for every font on its site. To use the font, you need to link that style sheet to your web page, or import Google’s style sheet into your style sheet (that’s the style.css file in the child theme). With WordPress, the second approach is easier.

Google gives you the code you need to add a font to your child theme’s style.css file.

Figure 13-12. Google gives you the code you need to add a font to your child theme’s style.css file.

5. Copy the @import line and then paste it into your style.css file.

Put it right after the @import line for the standard Twenty Twelve styles.

TIP

If you use several embedded fonts, you can add more than one @import command. However, there’s a slightly more efficient approach—if you create a font collection, Google gives you a single @import line that grants you use of all the fonts you picked.

6. Create a style that uses the font.

Once you import the Google style sheet, you can use your new font, by name, wherever you want. Just set the font-family property, as you would with a normal web-safe font. But remember to add a true web-safe font name after it as a fallback, in case you’re dealing with an old-school browser that can’t display embedded fonts or can’t download the font file.

Here’s a complete style.css file that uses this technique. The newly added parts are highlighted in bold.

/*

Theme Name: Twenty Twelve Reboot

Description: This is a customized version of the Twenty Twelve Theme for the

Magic Tea House.

Author: Katya Greenview

Template: twentytwelve

*/

@import url("../twentytwelve/style.css");

@import url(http://fonts.googleapis.com/css?family=Bonbon);

.entry-header .entry-title {

font-family: 'Bonbon', 'Times New Roman';

font-size: 30px;

}

Figure 13-13 shows this font in action in a post.

The Bonbon font is perhaps not the best for this site, but it’s impossible to deny that it makes for eye-catching post titles.

Figure 13-13. The Bonbon font is perhaps not the best for this site, but it’s impossible to deny that it makes for eye-catching post titles.

Editing the Code in Your Theme

When you want to customize the appearance of a theme, the first place you should look is the style.css file. But if you need to make more dramatic changes—for example, revamp the layout, change the information in the post list, or add new widget areas—you have to go further. Your next step is to consider the theme’s template files.

A typical theme uses anywhere from a dozen to 50 templates. If you crack one open, you see a combination of HTML markup and PHP code. The PHP code is the magic ingredient—it triggers the specific WordPress actions that pull your content out of the database. Before WordPress sends a page to a visitor, it runs all the PHP code inside it.

Writing this code is a task that’s well beyond the average WordPress website owner. But that’s not a problem, because you don’t need to write the code yourself, even if you’re building a completely new theme. Instead, you take a ready-made page template that contains all the basic code andedit that file to your liking. Here are two ways you can do that:

§ Change the HTML markup. Maybe you don’t need to change the code in the template file at all. You might just need to modify the HTML that wraps around it. After all, it’s the HTML (in conjunction with the style sheet) that determines how your content looks and where it appears.

§ Modify the PHP code. You start with a template full of working code. Often, you can carefully modify this code, using the WordPress documentation, to change the way it works. For example, imagine you want the list of posts on the home page to show fewer posts, include just post titles or images instead of content, or show posts from a specific category. You can do all this by adjusting the code that’s already in the home page template.

Of course, the more thoroughly you want to edit the PHP, the more you need to learn. Eventually, you might pick up enough skills to be an accomplished PHP tweaker.

UP TO SPEED: LEARNING PHP

The actual syntax of the PHP language is beyond the scope of this book. If you want to develop ninja programming skills, there are plenty of great resources for learning PHP, whether you have a programming background or are just starting out. Don’t rush off just yet, however, because while learning PHP will definitely help you customize a WordPress theme, it may not help you as much as you expect.

Learning to customize a WordPress template is partially about learning PHP (because it helps to understand basic language details like loops, conditional logic, and functions). But it’s mostly about learning to use WordPress’s functions in PHP code (see the Note on Note for more about WordPress functions). For that reason, you’ll probably get more practical value out of studying WordPress functions than learning the entire language, unless you plan to someday write dynamic web pages of your own.

To get started with WordPress functions, check out the function reference at http://tinyurl.com/func-ref. To learn more about PHP, start with the absolute basics with the tutorial at http://tinyurl.com/ctzya55.

Introducing the Template Files

Every theme uses a slightly different assortment of templates. The WordPress staple Twenty Twelve uses a fairly typical set of about 30 templates.

You can recognize a template by the fact that its filename ends with .php. Although template files hold a mix of HTML and PHP, the .php extension tells WordPress that there’s code inside that the WordPress engine needs to run before it sends the final page to a browser.

Even though a template is just a mix of HTML and PHP, understanding where it fits into your site can be a bit of a challenge. That’s because every page WordPress stitches together uses several template files.

For example, imagine you click through to a single post. WordPress has a template, called single.php, that creates the page on the fly. However, single.php needs help from a host of other templates. First, it inserts the contents of the header.php template, which sits at the top of every page in a WordPress site. The header.php file takes care of basics, like linking to the style sheet, registering some scripts, and showing the header section, complete with the top-level menu. (Some themes farm out the menu-creation work to yet another template file, but Twenty Twelve doesn’t go that far.)

Next, the single.php file adds the Previous and Next navigation links to the post, and then calls out to another template to display the actual post. If it’s a regular post, it uses content.php, but the Twenty Twelve theme has a number of specialized alternatives for different post formats. For example, an “aside” post (Applying a Post Format) uses the content-aside.php template, a “status” post uses content-status.php, and so on.

Finally, the single.php template ends by calling three more templates into action. The comments.php template creates the comments section, the sidebar.php template adds the widgets on the right, and the footer.php template ends the page.

If you’re going cross-eyed trying to follow this template assortment, Figure 13-14 shows how it all breaks down.

At first glance, this system seems just a bit bonkers. How better to complicate life than to split the code for a single page into a handful of template files that need to work together? But in typical WordPress fashion, the design is actually pretty brilliant. It means that a theme designer can create a single template file that governs a repeating site element—like a header—and use it everywhere, without needing to worry about duplicating effort or being inconsistent.

When you edit theme styles, your first challenge is finding the right style rule to change. When you edit templates, the first challenge is finding the right template file to modify. Table 13-2 can help you get started. It describes the fundamental templates that almost every theme, including Twenty Twelve, uses.

When you view a single post, the single.php template is in charge. It calls for help from several other templates.

Figure 13-14. When you view a single post, the single.php template is in charge. It calls for help from several other templates.

Keep in mind, however, that themes commonly add extra templates to create the formats for different types of posts and pages, and to handle special formatting (for example, to create different layouts that move the sidebar around). You may also decide to add extra templates of your own (for example, to change the way your site presents specific categories or authors, a technique you’ll see in Chapter 14).

Table 13-2. Essential WordPress templates

TEMPLATE FILE

DESCRIPTION

index.php

This is a theme’s main template, and the only one that’s absolutely required. WordPress uses it if there’s no other, more specific template to use. Most themes use index.php to display a list of posts on the home page.

header.php

Displays the banner that appears across the top of every page. Often, header.php includes a navigation menu.

footer.php

Displays the footer that stretches across the bottom of every page.

sidebar.php

Shows the sidebar widget area. Twenty Twelve also has a more specialized sidebar-front.php template that creates the footer area for pages that use the Front Page template.

single.php

Displays a single post.

page.php

Shows a static page. Themes often have additional page templates that let you create different “flavors” of pages (Page Templates). For example, Twenty Twelve adds a full-width.php template that creates a page that doesn’t include a sidebar and a front-page.php template that includes a two-column widget area in the footer.

content.php

Displays the content of a post or page. Some themes create many different content templates, for different types of posts and pages. Twenty Twelve, for instance, has eight content templates. An ordinary post uses content.php, a page uses content-page.php, and special post formats (Post Formats) use a corresponding template (for example, asides use content-aside.php).

comments.php

Displays the comments section after a post or page.

image.php

Shows the attachment page for images—what you see when you click a picture in a post, if you’ve set the Link To setting (Creating a Gallery) to Attachment Page.

archive.php

Lists posts when you browse by author, category, tag, or date. Or you can use one of the four more specific templates listed next.

category.php

Lists posts when you browse a category. You can also create templates that target specific categories, like category-tea.php for a category with “tea” as its simplified name (Browsing Categories and Tags Using a Web Address).

tag.php

Lists posts when you browse by tag. You can also create templates that target specific tags, like tag-promotion.php.

author.php

Lists posts when you browse by author. You can also create templates that target specific authors, like author-grabinksy.php.

search.php

Lists posts after you execute a search.

404.php

Displays an error message when the requested post or page can’t be found.

A Basic Editing Example

By this point, you’ve digested a fair bit of WordPress theory. It’s time to capitalize on that by editing a template file.

You’ll begin with an example that seems simple enough. You want to remove the “Proudly powered by WordPress” message that appears at the bottom of every page on your site, just under the footer widgets (Figure 13-15). (It’s not that you’re embarrassed by WordPress. You just can’t help but notice that none of the other big-gun WordPress sites have this message slapped on their pages. Sometimes, being professional means being discreet.)

Top: The way the Twenty Twelve footer looks ordinarily.Bottom: The footer after you customize it.

Figure 13-15. Top: The way the Twenty Twelve footer looks ordinarily. Bottom: The footer after you customize it.

Step 1. Find the Template File

Start by examining the list of templates in Table 13-2. In this case, the footer.php file is the obvious candidate. It creates the entire footer section, widgets and all, for every page.

Step 2. Create a Copy of the Template File

Once again, you need to start with a child theme (Protecting Yourself with a Child Theme). If you don’t, you can still customize the footer, but your hard-won changes will vaporize the moment you install a theme update.

Here’s where things get a bit more awkward. As you know, WordPress templates are really a collection of many template files. To change a template, you need to figure out the changes you want to make to your pages, and then find the template file responsible for that part of the page (single.php, comment.php, and so on). Then you add a new version of that template file to the child theme. That new template will override the one in the parent theme.

You do this by copying the template file you want to edit from the parent theme to your child theme and then making your changes. In this example, that means you need to copy the footer.php file in the twentytwelve folder and paste it into the twenty-twelve-reboot folder.

Unfortunately, the dashboard doesn’t have any tools to help you copy a template. The quickest and most straightforward solution is to use an FTP tool. First, copy the file (say, footer.php) from the parent theme folder (twentytwelve) to your computer. Second, copy that file from your computer to the child theme folder (twenty-twelve-reboot). Job done. You can now choose Appearance→Editor and start modifying the newly copied template.

If you don’t feel comfortable doing that, it’s plug-in time. This time, the solution is the Orbisius Child Theme Creator (http://tinyurl.com/orb-theme), which creates child themes and helps you create and copy templates. Install it, activate it, and then choose Appearance→Orbisius Theme Editor. You see a two-part page that lets you view and edit two themes side by side (Figure 13-16).

Orbisius doesn’t let you copy a template file directly, but it does something almost as good: It lets you create a new blank template file in your child theme, and then copy the content of the parent’s template into that new file. Here’s how:

1. In the Theme #1 box, pick your child theme, if it isn’t already selected.

2. Underneath the editing box on the left, click New File.

A few more options drop into view.

3. In the New File text box, type the exact name of the template you want to create (such as footer.php), and then click the Save button underneath.

This creates a new template file in your child theme and loads it up in the editing box on the left. However, there’s nothing in the file yet.

Using the Orbisius Theme Editor plug-in, you can compare any two themes by picking from the Theme #1 and Theme #2 lists. However, it makes the most sense to load up your current child theme on the left (which Orbisius does automatically) and choose the parent theme on the right.

Figure 13-16. Using the Orbisius Theme Editor plug-in, you can compare any two themes by picking from the Theme #1 and Theme #2 lists. However, it makes the most sense to load up your current child theme on the left (which Orbisius does automatically) and choose the parent theme on the right.

4. In the Theme #2 box, pick your parent theme. Then, in the adjacent File box, pick the name of the template you want to copy.

In this case, that’s footer.php. When you pick a file, you see the content of the template in the editing box underneath.

5. Copy the template markup from the old template file (on the right) to the new template file (on the left).

To do this, select the full text of the markup in the original template file on the right (in this case, that’s footer.php). Click at the very beginning of the file and then press Ctrl+A (Command+A on a Mac) to select all the content. Then press Ctrl+C (Command+C on a Mac) to copy the content. Lastly, click in the blank editing box on the left, and then press Ctrl+V (Command+V on a Mac) to paste it in.

6. Click Save Changes underneath the editing box on the left.

Now the new template in your child theme has the same content as the original template in the parent theme. This is the best starting point for your changes.

From this point on, it makes no difference whether you edit the new template file in the Orbisius page or in the Edit Themes page (which you open by choosing Appearance→Editor).

NOTE

The child theme’s version of a template completely overrides the parent theme’s copy of the template. In this example, that means WordPress ignores the original version of the footer.php file, which is in the original theme folder (twentytwelve). You can refer to it anytime to check the code or copy important bits, but WordPress won’t run the code anymore.

Step 3. Examine the Template File

Footer.php is one of WordPress’s simpler template files. But even simple templates have a fair bit of boilerplate to wade through.

In this section, you’ll look at the entire contents of footer.php. You don’t always need to take this step, but it’s good practice when you’re just starting out and trying to make sense of WordPress’s template system.

If you’ve written web pages before, you probably know that programming code, like JavaScript, needs to be carefully separated from the HTML on the page. The same is true for PHP, although it has its own special syntax. Every time a block of PHP code appears, it starts with this:

<?php

Similarly, the following character sequence marks the end of a block of PHP code:

?>

You can see this system at work at the very beginning of every template file, where there’s a block of PHP that has no real code at all, just a long comment. The comment lists some basic information about the template. Here’s what you see in footer.php:

<?php

/**

* The template for displaying the footer.

*

* Contains footer content and the closing of the #main and #page div ele-

ments.

*

* @package WordPress

* @subpackage Twenty_Twelve

* @since Twenty Twelve 1.0

*/

?>

The next line is a puzzling bit of HTML that looks like this:

</div><!-- #main .wrapper -->

Even seasoned HTML veterans will be a bit thrown off here. The </div> tag closes a <div> element. But you haven’t seen an opening <div> tag, so this code snippet seems a bit strange.

It makes more sense when you remember the way WordPress stitches together a page, as shown in Figure 13-14. The <div> element was opened, but it happened when WordPress processed an earlier template file (header.php). The HTML comment in the line above (<!--#main .wrapper -->) is WordPress’s way of reminding you that the </div> in that line is the closing element for a <div> that has the ID main and the class .wrapper. In other words, it’s the closing element for the <div> that holds the main content of the page.

The next line of HTML is easier to interpret. It identifies the beginning of the footer content. This section has the ID colophon, which you might remember from Table 13-1.

<footer id="colophon" role="contentinfo">

The next line starts a new <div> element and gives it the ID site-info. The creators of the Twenty Twelve theme chose that name because this is the section of the page that indicates some basic information about how the site was created (in other words, “Proudly powered by WordPress”).

<div id="site-info">

The next bit is another block of PHP code, but it’s compressed into a single line:

<?php do_action( 'twentytwelve_credits' ); ?>

The do_action() function is a WordPress feature found throughout its template files. It’s a notification mechanism—it signals when something is about to happen (for example, that the page credits are about to be shown). Hardcore WordPress developers can write instructions that react to one of these notifications, but the do_action() function is no help in your mission to change the footer.

NOTE

A function is a block of programming code stored somewhere other than the page it appears on. WordPress is full of useful functions, and do_action() is one of many. To browse the full catalog of functions and find out what they do, visit http://tinyurl.com/func-ref.

The section that appears after the do_action() function is the part of the footer template you’ve been looking for. It’s a link that displays the “Proudly powered” message:

<a href=

"<?php echo esc_url( __( 'http://wordpress.org/', 'twentytwelve' ) ); ?>"

title= "<?php esc_attr_e( 'Semantic Personal Publishing Platform',

'twentytwelve'); ?>" rel="generator">

<?php printf( __( 'Proudly powered by %s', 'twentytwelve' ),

'WordPress'); ?>

</a>

The markup looks a bit complicated, because there are three PHP code statements embedded inside the <a> element. The first one generates the actual link address, the second one generates the title, and the third one generates the text inside the <a> element. You don’t need to understand exactly how these statements work to realize that this is the part you want to change. But first, scan through the rest of the footer template to make sure you understand what’s going on.

It’s pretty straightforward. First, footer.php closes the <div> and <footer> elements. Then it closes another <div> that represents the entire page.

</div><!-- .site-info -->

</footer><!-- #colophon -->

</div><!-- #page -->

Next, the footer template triggers WordPress’s wp_footer() function.

<?php wp_footer(); ?>

This is a bit of WordPress infrastructure. Many plug-ins wait for this call and then do something important. Removing this line can cause those plug-ins to break, so it’s best to leave it in, even though it isn’t doing anything right now.

Finally, the template closes the <body> and <html> elements, proving that you have really and truly reached the end of the page. WordPress won’t call any more templates into action, or add any more content after this point.

</body>

</html>

Step 4. Make Your Change

Now you’ve found the culprit—the piece of the WordPress template you want to change. In this example, it’s a single <a> element.

You could delete the <a> element completely, or you can replace it with some text of your own, like this:

© Copyright 2014 Magic Tea House

The © is a character entity, an HTML code that inserts a special character—in this case, a copyright symbol.

If you consider yourself a bit of a PHP whiz, you can get fancier in your footer. For example, instead of sticking in the current year for the copyright notice, you could ask PHP to do that for you.

First, you need to explicitly tell WordPress that you need PHP’s help. You do that by adding the <?php and ?> character sequences. You’ll put your code inside.

© Copyright <?php [ Your code goes here. ]

?> by Magic Tea House

Next, you need a PHP command. In this case, it’s the trusty echo command, which means (in PHP language) “take the result of the next statement, and spit it out onto the page.”

© Copyright <?php echo ?> by Magic Tea House

But what exactly do you want to spit out? That’s the current date, which you can fetch with the help of a function built into the PHP language, called date(). Unsurprisingly, the date() function displays the current date. But by supplying the capital letter Y, you tell the date() function that you’re interested only in getting the current year.

© Copyright <?php echo date('Y'); ?> by Magic Tea Ho

use

Like every line of PHP code, you indicate the end of a statement by adding a semicolon at the end (;)

This completes the example, and drives home a clear point: Even the most straightforward theme-editing tasks require a bit of slogging.

TIP

Since the changes you need to make to the footer.php template are relatively small in this example, it’s easy enough to do all your editing in the dashboard. For more significant changes, you may want to copy the theme file to a text editor on your computer, work with it there, and then copy it back to the Edit Themes page when you finish. And if you decide to edit a theme on your computer, it’s worth considering a text editor that has a few more frills. For example, Windows users can grab the free Notepad++ program (http://notepad-plus-plus.org), which uses color-coded text to distinguish the different ingredients in PHP code.

FREQUENTLY ASKED QUESTION: UPDATING A CHILD THEME

What happens when I update a theme that uses customized templates?

Child templates don’t work in exactly the same as child styles. Child styles extend style rules already put in place by the parent theme. Even if the parent gets a new, updated style.css file, the child styles remain, and WordPress applies them on top of the parent styles.

But page templates don’t extend parent templates, they replace them. As soon as you add footer.php to your child theme, WordPress starts ignoring the footer.php in the original theme. That means that if you update the parent theme and change the original footer.php file, no one really notices.

This is probably the safest way to handle theme updates, because there really isn’t a way that WordPress could combine two versions of a template. However, it means that if you plan to customize all the templates in a theme, you probably shouldn’t create a child theme. Instead, you may as well build a completely separate theme of your own.

Delving into the Loop

WordPress experts talk in hushed tones about “the loop,” which is the heart of WordPress. Its job is to fetch content from your website’s database, one piece at a time, until it reaches the post limit (that’s the “Blog pages show at most” option in the Settings→Reading section of the dashboard).

The loop appears in many templates. WordPress uses it to create the main list of posts on the home page (index.php), the list of results after a search (search.php), and the list of articles you see when you browse by category, tag, author, or date (category.php, tag.php, author.php, anddate.php, or archive.php when one of the former is missing). The loop even appears on Twenty Twelve’s showcase page (showcase.php), twice—first to grab the featured posts that it puts up top, and again to grab the recent posts that it shows underneath. (Showcase pages are explained onBetter Home Pages.)

In the following example, you’ll take a look at the loop in the index.php file and change the way it works by adding a new feature: the ability to highlight recent posts (Figure 13-17).

Step 1. Prepare the Template File

Your first task is to prepare your template. You can copy the index.php file into your child theme folder using an FTP program, or you can use the Orbisius Child Theme Creator plug-in to copy it for you.

This page gives the “Tea Sale” post, which was published today, preferential treatment—it gets a bigger headline, a border, and a yellow background. Tomorrow, the post will revert to its normal look.

Figure 13-17. This page gives the “Tea Sale” post, which was published today, preferential treatment—it gets a bigger headline, a border, and a yellow background. Tomorrow, the post will revert to its normal look.

Step 2. Examine the Template File

The next step is to dig through index.php to get a handle on what’s going on and what area you need to change. Overall, index.php has this structure:

<?php get_header(); ?>

<div id="primary">

<div id="content" role="main">

[ The stuff for displaying posts goes here. ]

</div><!-- #content -->

</div><!-- #primary -->

<?php get_sidebar(); ?>

<?php get_footer(); ?>

This boils the template down to its essentials. As you can see, the template calls other templates to create the page’s header, sidebar, and footer. In the middle of this action are two <div> elements, and inside them is the heart of the index.php template and the loop. This is the part you’ll focus on.

The first ingredient here, inside the <div> elements, is a block of conditional logic—code that tests a condition, and takes different actions depending on whether that condition is true or false. Essentially, the template here uses PHP to ask a question: Are there any posts?

Here’s how the template structures the conditional logic:

<?php if ( have_posts() ) : ?>

[ If there are posts, you end up here. ]

<?php else : ?>

[ If there are no posts, this section shows the "sorry" message.]

<?php endif; ?>

The have_posts() function gets the answer to the question, “Are there any posts?” If there are, the condition is true, and the first section springs into action. That’s the part you’re interested in. (If there aren’t any posts, the condition is false, and you can let the template handle it in the usual fashion, by showing an apologetic message.)

So what takes place inside the first section, which runs as long as your site has at least one post? The code starts by adding a navigation link, if necessary. This is the link that appears before the post list and lets visitors step forward to newer posts. (If your guest is already viewing the most recent post, this link doesn’t show up.) Then the code triggers the loop (shown here in bold), and ends by inserting another navigation link—the one that lets readers step back to see older posts.

<?php twentytwelve_content_nav( 'nav-above' ); ?>

<?php while ( have_posts() ) : the_post(); ?>

<?php get_template_part( 'content', get_post_format() ); ?>

<?php endwhile; ?>

<?php twentytwelve_content_nav( 'nav-below' ); ?>

The actual loop comes down to just three lines. The while and endwhile commands delineate the start and end of the loop. As long as you have posts, the loop keeps running. Every time it runs, it grabs a post, using the WordPress function the_post(), and feeds it to the single line of code inside. This code is less exciting—it simply farms out the work of displaying the post to one of the content templates you learned about earlier, using the get_template_part() function.

Although the code doesn’t seem that exciting right now, there’s a lot you can do if you wedge yourself inside the loop, between the while and endwhile lines. Currently, there’s just a single line of code there, but you can expand it to suit your needs. For example, before the code callsget_template_part() to display a post, you can run some extra code that does something more clever, like change the post’s formatting based on one of the post details. Examples include making the post look different based on its category, author, or publication date. The latter is what this example does.

Step 3. Add New Code

The final step is to add the code that checks the post’s date and decides whether or not to highlight it. Here it is, inside the loop you saw earlier. The new code is boldfaced:

<?php while ( have_posts() ) : the_post(); ?>

<?php

$postdate = get_the_date('Y-m-d');

$currentdate =

date('Y-m-d',mktime(0,0,0,date('m'),date('d'),date('Y')));

if ($postdate == $currentdate) {

echo '<div class="newpost">';

} else {

echo '<div>';

}

?>

<?php get_template_part( 'content', get_post_format() ); ?>

</div>

<?php endwhile; ?>

To understand what’s taking place, you need to examine the code one line at a time. First, it uses a WordPress function named get_the_date(), which returns the date the current post was published.

$postdate = get_the_time('Y-m-d');

WordPress takes the result from get_the_date() and puts it into a variable (a storage slot in memory) named $postdate. That way, the code can use the date stored there at a later time, when the function compares dates.

NOTE

It doesn’t matter what you call your variables, as long as you’re consistent. (So you can’t call the variable $postdate in one place and $date_of_post in another, because you’ll end up creating two separate variables.) However, your variable names must start with the dollar sign ($), which has the side effect of making them easily recognizable.

The next line of code creates a second variable, named $currentdate. It stores the current date, as retrieved by the PHP date() function, which you saw earlier (Step 4. Make Your Change). Only now the date is returned in a slightly different format, so it matches up with the publication date format WordPress uses with posts.

$currentdate = date('Y-m-d');

The moment of drama occurs next. An if statement compares the two variables (in this case, the two dates) to see if the current date matches the publication date (in other words, to see if the post was published today). If the answer is yes, then the code adds a new <div> element, with the class name newpost.

if ($postdate == $currentdate) {

echo '<div class="newpost">';

If the answer is no, then the code adds a <div> that doesn’t use any class name.

} else {

echo '<div>';

}

?>

Either way, the code tacks on the closing </div> element at the end of this block of content, after it inserts the post content into the page.

<?php get_template_part( 'content', get_post_format() ); ?>

</div>

NOTE

This code may seem slightly magical, because it relies on a tight combination of PHP commands and WordPress functions that you haven’t seen before. Obviously, you wouldn’t be able to cook up this sort of code on your own. However, you will be able to grab this sort of code from one of the many WordPress recipe sites (Extending WordPress with Functions.php), and insert it into your templates when you need it. And the more you do that, the easier it’ll be to recognize the code you want to change, and the more comfortable you’ll be adjusting that code to solve a problem.

Step 4. Add a New Style

Right now, the revised template doesn’t have much of an effect. All it does is add a <div> element around the post content. However, this <div> gives you a new way to apply a customized style. You do that by creating a style rule for the newpost class.

Here are the style rules that create the effect shown in Figure 13-17. The first rule adds the border, spacing, and background color around the post. The second rule targets the link in the heading, which holds the post title, and gives it large red text.

.newpost {

padding: 8px;

border: 2px solid darkgray;

border-radius: 10px;

background-color: lightyellow;

margin-bottom: 50px;

}

.newpost h1 a {

font-size: 2.5em;

color: red;

}

This two-part approach—using the PHP code to add a style, and then defining the style—is a common technique in theme customization. It gives you the most flexibility, because you can change the formatting anytime, without editing the template and wading through the PHP again.

Extending WordPress with Functions.php

Some WordPress themes contain one PHP file that isn’t a template, named functions.php. Experienced theme designers place important parts of their code here, and then call that code from their template files when they need it. WordPress gurus also use the functions.php file to add other features, like new shortcodes and widgets, so they don’t need to create a complete plug-in.

All these tasks are advanced operations, best kept to WordPress gurus. However, even people with no PHP experience can use the functions.php file to unlock extra WordPress features. Usually, you do that by copying a few lines of code you read about online (or in a book), and pasting them into the functions.php file in the theme editor.

For example, in Chapter 10, you used WordPress’s auto-embed feature to turn certain types of website addresses into embedded objects, like Flickr slideshows and YouTube videos. Normally, WordPress turns off this handy feature in widget areas, like the sidebar. But those in the know can enable shortcodes and embeds in widget areas with just a couple of lines in the functions.php file. Figure 13-18 shows the result.

The functions.php file works a bit differently from the template files you’ve learned about so far. The key quirk is that the functions.php file in your child theme extends the functions.php file in your parent theme; it doesn’t replace it. For that reason, you can’t simply copy the functions.phpfile from your parent theme to your child theme. You need to create a new, empty text file on your computer, change its name to functions.php, and then upload that new functions.php file to your child theme folder.

If you use the Orbisius Child Theme Creator plug-in, your job is easy. Follow the process described on Step 1. Find the Template File to create a new, blank functions.php file, but don’t copy any content to that file.

This sidebar holds a miniature YouTube video, courtesy of the Text widget and the auto-embed feature.

Figure 13-18. This sidebar holds a miniature YouTube video, courtesy of the Text widget and the auto-embed feature.

WARNING

If you accidentally copy the functions.php file from your parent theme to your child theme, your site will stop working. That’s because functions.php is full of important routines that Twenty Twelve uses, and having two copies of this code is enough to blow WordPress’s mind. The only fix (if you disregard this warning and put the full functions.php file in your child theme folder) is to log in to your site with an FTP program and delete the copied functions.php file.

Once you add the blank functions.php file to your site, you can edit it in the Edit Theme page, as you can any other theme file. To enable widget-embedding, as shown in Figure 13-18, you need to add these lines:

<?php

add_filter( 'widget_text', array( $wp_embed, 'run_shortcode' ), 8);

add_filter( 'widget_text', array( $wp_embed, 'autoembed'), 8 );

?>

Now you can put an auto-embed URL in a Text widget, just as you can in a post (Figure 13-19).

Thanks to WordPress’s auto-embed feature, which you’ve now enabled for widgets, this URL will turn into a tiny video box. Note that it uses the width attribute to shrink the box down to 300 pixels wide, so it fits comfortably in the sidebar.

Figure 13-19. Thanks to WordPress’s auto-embed feature, which you’ve now enabled for widgets, this URL will turn into a tiny video box. Note that it uses the width attribute to shrink the box down to 300 pixels wide, so it fits comfortably in the sidebar.

POWER USERS’ CLINIC: LEARNING MORE ABOUT THEME CUSTOMIZATION

This chapter offers a glimpse of the styles, templates, and PHP code that underpins WordPress. Even if you don’t understand how it all works (and most people don’t), you still know enough to start making template changes. You may need trial-and-error experimentation to get the result you want, and you may need to search for other people’s hacks and tricks to help you out (Google is your friend). But as long as you’re not afraid to open a template file, look inside, and make changes, you have the potential to change anything.

In the next chapter, you’ll methodically explore a complete end-to-end site example. In the meantime, it’s worth pointing out some resources you can use to develop your theme-tweaking skills:

§ Template recipes. You can practice a grab bag of simple theme tricks at http://tinyurl.com/templatetrix. They’re divided into short, practical chunks. The more you try out, the more comfortable you’ll become navigating the tangled maze of templates that constitute a theme.

§ Blogs by WordPress pros. Lorelle van Fossen (http://lorelle.wordpress.com) has acres of practical content about customizing WordPress sites, including many adventures in theme customization.

§ Smashing Magazine. If you’re looking to get more serious, Smashing Magazine (http://wp.smashingmagazine.com) has hardcore articles about every aspect of WordPress site development. They often go far beyond ordinary features and deep into theme customization.

§ Theme frameworks. Theme frameworks extend the core WordPress code with new features. The cost is extra complexity, although you won’t need to fiddle with low-level details and PHP code anymore. Popular examples include Thematic (http://tinyurl.com/themat), which is free, and Genesis (http://tinyurl.com/gen-theme), which isn’t.