Chapter 3

Exploring the Anatomy of a Theme

IN THIS CHAPTER

Check Examining the theme’s stylesheet

Check Exploring template tags

Check Making widget areas

Check Understanding the main template files

This chapter breaks down the parts that make up your WordPress theme. Understanding your theme allows you greater flexibility when you customize it. Many of the problems people encounter with themes, such as not knowing which files edit certain functions of a site, comes from lack of understanding all the pieces.

If, like me, you like to get your hands dirty, you need to read this chapter. WordPress users who create their own themes do so in the interest of

  • Individuality: Having a theme that no one else has. (If you use one of the free themes, you can pretty much count on the fact that at least a dozen other WordPress blogs have the same look as yours.)
  • Creativity: Displaying your personal flair and style.
  • Control: Having full control of how the blog looks, acts, and delivers your content.

Many of you aren’t at all interested in creating your own theme for your WordPress website, however. Sometimes, it’s easier to leave matters to the professionals and hire an experienced WordPress theme developer to create a custom look for your WordPress website or to use one of the thousands of free themes provided by WordPress designers. (See Book 6, Chapter 2.)

Creating themes requires you to step into the code of the templates, which can be a scary place sometimes, especially if you don’t know what you’re looking at. A good place to start is by understanding the structure of a WordPress website. Separately, the parts won’t do you any good. But when you put them together, the real magic begins! This chapter covers the basics of doing just that, and near the end of the chapter, you find specific steps for putting your own theme together.

Tip You don’t need to know HTML to use WordPress. If you plan to create and design WordPress themes, however, you need some basic knowledge of HTML and Cascading Style Sheets (CSS). For assistance with HTML, check out HTML5 and CSS3 All-in-One For Dummies, 3rd Edition, by Andy Harris (John Wiley & Sons, Inc.).

Starting with the Basics

A WordPress theme is a collection of WordPress templates made up of WordPress template tags. When I refer to a WordPress theme, I’m talking about the group of templates that makes up the theme. When I talk about a WordPress template, I’m referring to only one of the template files that contain WordPress template tags and functions. WordPress template tags make all the templates work together as a theme. (I cover this topic in the Exploring Template Tags, Values, and Parameters section later in this chapter) These files include

  • The theme’s stylesheet (style.css): The stylesheet provides the theme's name, as well as the CSS rules that apply to the theme. (Later in this chapter, I go into detail about how stylesheets work.)
  • The main index template (index.php): The index file is the first file that will be loaded when a visitor comes to your site. It contains the HTML as well as any WordPress functions and template tags needed on your home page.
  • An optional functions file (functions.php): This optional file is a place where you can add additional functionality to your site via PHP and/or WordPress-specific functions.

Template and functions files end with the .php extension. PHP is the scripting language used in WordPress, which your web server recognizes and interprets as such. (Book 2, Chapter 3 covers additional details on the PHP language that you'll find helpful.) These files contain more than just scripts, though. The PHP files also contain HTML markup, which is the basic markup language of web pages.

Within this set of PHP files is all the information your browser and web server need to make your website. Everything from the color of the background to the layout of the content is contained in this set of files.

Remember The difference between a template and a theme can cause confusion. Templates are individual files. Each template file provides the structure in which your content will display. A theme is a set of templates. The theme uses the templates to make the whole site.

Understanding where the WordPress theme files are located on your web server gives you the ability to find and edit them, as needed. You can use two different methods to view and edit WordPress theme files by following these steps:

  1. Connect to your web server via Secure FTP (SFTP), and have a look at the existing WordPress themes on your server.

    The correct location is /wp-content/themes/. When you open this folder, you find the /twentynineteen theme folder, which is the default theme for WordPress.

    Remember If a theme is uploaded to any folder other than /wp-content/themes, it won't work.

  2. Open the folder for the Twenty Nineteen theme (/wp-content/themes/twentynineteen), and look at the template files inside.

    When you open the Twenty Nineteen theme folder (see Figure 3-1), you see several files. At minimum, you find these five templates in the default theme:

    • Stylesheet (style.css)
    • Functions file (functions.php)
    • Header template (header.php)
    • Main index (index.php)
    • Footer template (footer.php)

    These files are the main WordPress template files, and I discuss them in more detail in this chapter. There are several template files, however, and you should try to explore all of them if you can. Take a peek inside to see the different template functions they contain. Every WordPress theme is different and contains a different number and type of files, but the five files I mention here usually exist in all WordPress themes.

  3. Click the Editor link on the Appearance menu to look at the template files within a theme.

    This Edit Themes page lists the various templates available within the active theme. (Figure 3-2 shows the templates in the default Twenty Nineteen theme.) A text box in the middle of the screen displays the contents of each template, and this box is also where you can edit the template file(s). To view and edit a template file, click the template's name in the list on the right side of the page.

Screenshot of the FileZilla page displaying a list of template files contained within the Twenty Nineteen theme folder.

FIGURE 3-1: Template files contained within the Twenty Nineteen theme folder.

Screenshot of the Edit Themes screen displaying a list of templates available in the default Twenty Nineteen theme.

FIGURE 3-2: A list of templates available in the default Twenty Nineteen theme.

The Edit Themes page also shows the HTML markup and template tags within the template file. These tags make all the magic happen on your website; they connect all the templates to form a theme. “Connecting the templates” later in this chapter discusses these template tags in detail, showing you what they mean and how they function. “Putting a Theme Together” later in this chapter provides steps for putting the tags together to create your own theme or edit an existing theme.

Tip Click the Documentation drop-down menu on the Themes screen (as shown in Figure 3-3) to see all the template tags used in the template you’re currently viewing. This list is helpful when you edit templates, and it gives you insight into the template tags used to create functions and features in the template you’re viewing. (Note: The Documentation drop-down menu on the Themes screen doesn’t appear when you view the stylesheet because no template tags, or functions, are used in the style.css template — only CSS.)

Screenshot of the Edit Themes screen of the Dashboard displaying the Documentation drop down menu with selected file content.

FIGURE 3-3 The Documentation drop down menu on the Edit Themes screen.

Understanding the Stylesheet

Every WordPress theme includes a style.css file. A browser uses this file, commonly known as the stylesheet, to style the theme. Style can include text colors, background images, and the spacing between elements on the site. The stylesheet targets areas of the site to style by using CSS IDs and classes. CSS IDs and classes are means of naming particular elements of the site. IDs are used for elements that appear only once on a page, but classes can be used as many times as you need. Although this file references style, it contains much more information about the theme.

At the beginning of the style.css file, a comment block known as the stylesheet header passes information about your theme to WordPress. Comments are code statements included only for programmers, developers, and any others who read the code. Computers ignore comment statements, but WordPress uses the stylesheet header to get information about your theme. In CSS, comments always begin with a forward slash (/) followed by a star (*) and end with a star followed by a forward slash (*/). The following code shows an example of the stylesheet header for the Twenty Nineteen theme:

/*
Theme Name: Twenty Nineteen
Theme URI: https://github.com/WordPress/twentynineteen
Author: the WordPress team
Author URI: https://wordpress.org/
Description: A new Gutenberg-ready theme.
Requires at least: WordPress 4.9.6
Version: 1.0
License: GNU General Public License v2 or later
License URI: LICENSE
Text Domain: twentynineteen
Tags: custom-background, custom-logo, custom-menu, featured-images, threaded
comments, translation-ready

This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned
With others.

Twenty Nineteen is based on Underscores https://underscores.me/, (C) 2012-2018
Automattic, Inc. Underscores is distributed under the terms of the GNU GPL v2
or later.

Normalizing styles have been helped along thanks to the fine work of
Nicolas Gallagher and Jonathan Neal https://necolas.github.io/normalize.css/
*/
/*--------------------------------------------------------------
>>> TABLE OF CONTENTS:
----------------------------------------------------------------
# Variables
# Normalize
# Typography
## Headings
. ## Copy
# Elements
. ## Lists
. ## Tables
# Forms
. ## Buttons
. ## Fields
# Navigation
. ## Links
. ## Menus
. ## Next & Previous
# Accessibility
# Alignments
# Clearings
# Layout
# Widgets
# Content
. ## Archives
. ## Posts and pages
. ## Comments
# Blocks
# Media
. ## Captions
. ## Galleries
--------------------------------------------------------------*/
/*
* Chrome renders extra-wide   characters for the Hoefler Text font.
* This results in a jumping cursor when typing in both the Classic and block
* editors. The following font-face override fixes the issue by manually
* inserting a custom font that includes just a Hoefler Text space replacement
* for that character instead.
*/

Figure 3-4 shows how the Twenty Nineteen theme information looks on the Themes screen in the Dashboard. Notice that the Title, Author, Description, Version, and Tags information is pulled directly from the style.css header.

Screenshot of the Manage Themes screen of the Dashboard displaying the Twenty Nineteen information.

FIGURE 3-4: Twenty Nineteen information on the Themes screen of the Dashboard.

If you make modifications to the stylesheet header, the changes reflect in the WordPress Dashboard on the Themes screen, found by clicking the Theme link in the Appearance menu.

Warning Themes must provide this information in the stylesheet header, and no two themes can have the same information. Two themes with the same name and details would cause a conflict in the theme-selection page. If you create your own theme based on another theme, make sure that you change this information first.

Below the stylesheet header are the CSS styles that drive the formatting and styling of your theme.

Tip Book 6, Chapter 4 goes into detail about CSS, including some examples that you can use to tweak the style of your existing WordPress theme. Check it out!

Exploring Template Tags, Values, and Parameters

Some people are intimidated when they look at template tags. Really, they're just simple bits of PHP code that you can use inside a template file to display information dynamically. Before starting to play around with template tags in your WordPress templates, however, it’s important to understand what makes up a template tag and why.

WordPress is based in PHP (a scripting language for creating web pages) and uses PHP commands to pull information from the MySQL database. Every tag begins with a function to start PHP and ends with a function to stop PHP. In the middle of those two commands lives the request to the database that tells WordPress to grab the data and display it.

A typical template tag looks like this:

<?php bloginfo();?>

This example tells WordPress to do three things:

  • Start PHP (<?php).
  • Use PHP to get information from the MySQL database and deliver it to your blog (bloginfo();).
  • Stop PHP (?>).

In this case, bloginfo is the actual tag, which grabs information from the database to deliver it to your site. What information is retrieved depends on what tag appears between the two PHP commands. As you may notice, there's a lot of starting and stopping of PHP throughout the WordPress templates. The process seems as though it would be resource-intensive, if not exhaustive, but it really isn’t.

Remember For every PHP command you start, you need a stop command. Every time a command begins with <?php, somewhere later in the code is the closing ?> command. PHP commands that aren't structured properly cause really ugly errors on your site, and they’ve been known to send programmers, developers, and hosting providers into loud screaming fits.

Understanding the basics

If every piece of content on your site were hard-coded (manually added to the template files), it wouldn’t be easy to use and modify. Template tags allow you to add content dynamically to your site. One example of adding information by using a template tag is the the_category tag. Instead of typing all the categories and links that each post belongs in, you can use the the_category() tag in your template to automatically display all the categories as links.

Using template tags prevents duplication of effort by automating the process of adding content to your website.

When you use a template tag, you're really telling WordPress to do something or retrieve some information. Often, template tags are used to fetch data from the server and even display it on the front end. More than 100 template tags are built into WordPress, and the tags vary greatly in what they can accomplish. You can find a complete list of template tags in the WordPress Codex (documentation for WordPress) at https://codex.wordpress.org/Template_Tags.

You can use template tags only inside PHP blocks. The PHP blocks can be opened and closed as many times as needed in a template file. When a PHP block is opened, the server knows that anything contained in the block is to be translated as PHP and then executed. The opening tag (<?php) must be followed at some point by the closing tag (?>). All blocks must contain these tags. A template tag is used in the same way that PHP functions are. The tag is always text (maybe separated with underscores or dashes), opening and closing brackets, and a semicolon. The following line of code (not a real template tag) shows you how everything looks:

<?php template_tag_name();?>

PHP is a fairly advanced coding language and has many built-in functions for you to use. If you aren't a PHP developer, keep it simple when you’re attempting to add custom PHP. All code must be semantically perfect; otherwise, it won’t work. Always read your code to make sure that you entered it correctly.

Remember You can use some template tags only inside The Loop, so check the Codex for details. You can find out more about The Loop in “Examining the Main Index and The Loop” later in this chapter.

Using parameters

Because a template tag is a PHP function, you can pass parameters to the tag. A parameter is a variable that allows you to change or filter the output of a template tag. WordPress has three types of template tags:

  • Tags without parameters: Some template tags don’t require any options, so they don’t need any parameters passed to them. The is_user_logged_in() tag, for example, doesn’t accept any parameters because it returns only true or false.
  • Tags with PHP function-style parameters: Template tags with PHP function-style parameters accept parameters that are passed to them by placing one or more values inside the function's parentheses. If you’re using the bloginfo() tag, for example, you can filter the output to the description by using

    <?php bloginfo('description');?>

    Remember If multiple parameters are involved, the order in which you list them is very important. Each function sets the necessary order of its variables, so double-check the order of your parameters.

    Remember Always place the value in single quotes, and separate multiple parameters with commas.

  • Tags with query-string-style parameters: Template tags’ query-string parameters allow you to change the values of only the parameters you need to change. This feature is useful for template tags that have a large number of options. The wp_list_authors(); tag, for example, has six parameters. Instead of using the PHP function-style parameters, you can get to the source of what you need and give it a value. If you want to see the full names of your authors in a list, for example, use

    <?php wp_list_authors('show_fullname=1');?>

    Query-string-style parameters can be the most difficult kinds to work with because they generally deal with the template tags that have the most possible parameters.

Table 3-1 helps you understand the three variations of parameters used by WordPress.

TABLE 3-1 Three Variations of Template Parameters

Variation

Description

Example

Tags without parameters

These tags have no additional options available. Tags without parameters have nothing within the parentheses.

the_tag();

Tags with PHP function-style parameters

These tags have a comma-separated list of values placed within the tag parentheses.

the_tag(‘1,2,3’);

Tags with query-string-style parameters

These types of tags have several available parameters. This tag style enables you to change the value for each parameter without being required to provide values for all available parameters for the tag.

the_tag(‘parameter=true’);

You need to know these three types of parameters:

  • String: A line of text that can be anything from a single letter to a long list of words. A string is placed between single quotation marks and sets an option for the parameter or is displayed as text.
  • Integer: A positive or negative number. Integers are placed within the parentheses and either inside or outside single quotation marks. Either way, WordPress processes them correctly.
  • Boolean: A parameter that sets the options to true or false. This parameter can be numeric (0=false and 1=true) or textual. Boolean values aren't placed within quotation marks.

Remember The WordPress Codex, located at https://codex.wordpress.org, has every conceivable template tag and possible parameter known to the WordPress software. The tags and parameters that I share with you in this chapter are the ones used most often.

Customizing common tags

Because template tags must be used inside the PHP template files, they can easily be customized with HTML. If you’re using the PHP tag wp_list_authors(), for example, you could display it in an HTML unordered list so that the pages are easily accessible to the users, like this:

<ul>
. <?php wp_list_authors('show_fullname=1');?>
</ul>

This code displays all the authors on your WordPress site as an unordered list like this:

  • John Doe
  • Jane Doe
  • Xavier Doe

Another example is titles. You can wrap the titles of your posts or pages in H1 HTML tags, like this:

<h1 class="pagetitle">
. <?php the_title();?>
</h1>

Creating New Widget Areas

Most themes are widget-ready, meaning that you can insert widgets into them easily. Widgets allow you to add functionality to your sidebar without having to use code. Some common widget functionalities include displaying recent posts, displaying recent comments, adding a search box for searching content on a site, and adding static text. Even widget-ready themes have their limitations, however. You may find that the theme you chose doesn't have widget-ready areas in all the places you want them. You can make your own, however.

Registering your widget

To add a widget-ready area to the WordPress Dashboard Widget interface, first you must register the widget in your theme's Functions file (functions.php) file by following these steps:

function my_widgets_init() {
register_sidebar(array (
'name' => __('My Widget Area'),
'id' => 'my-widget-area',
'description' => __('A new widget area I created!'),
'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
'after_widget' => "</li>",
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
));
}
add_action('widgets_init', 'my_widgets_init');

You can insert this code at the very bottom of the Functions file. It’s sometimes helpful to add a few extra lines when you’re adding code. The extra empty lines are ignored by the browser but greatly increase the readability of the code.

Within that code, you see an array with seven key pair values that tell WordPress how you want your widgets to be handled and displayed:

  • name: This name is unique to the widget and appears on the Widgets screen of the Dashboard. It's helpful to register several widget areas on your site.
  • id: This array is the unique ID given to the widget.
  • description (optional): This array is a text description of the widget. The text placed here displays on the Widgets screen of the Dashboard.
  • before_widget: This array is the HTML markup that gets inserted directly before the widget and is helpful for CSS styling purposes.
  • after_widget: This array is the HTML markup that gets inserted directly after the widget.
  • before_title: This array is the HTML markup that gets inserted directly before the widget title.
  • after_title: This array is the HTML markup that gets inserted directly after the widget title.

Remember Even though you use register_sidebar to register a widget, widgets don't have to appear on a sidebar; they can appear anywhere you want them to. The example code snippet earlier in this section registers a widget named Widget Name on the WordPress Dashboard. Additionally, it places the widget’s content in an element that has the CSS class widget and puts <h3> tags around the widget's title.

Widgets that have been registered on the WordPress Dashboard are ready to be populated with content. On the Appearance menu of your site’s Dashboard, you see a link titled Widgets. When you click the Widgets link, you see the new widget area you registered.

Displaying new widgets on your site

When a widget area is registered with WordPress, you can display the area somewhere on your site. Common places for widget areas are the sidebar and (in the default Twenty Nineteen theme) the footer.

To add a widget area to a template file in your WordPress theme, pick a location within the file and then locate that area in the HTML. (This area can vary from theme to theme.) Many times, theme authors will create their own sidebar.php or footer.php file, and you can add this code there. After you find the area in the HTML, add the following code to the template:

<?php dynamic_sidebar('My Widget Area');?>

This code displays the contents of the widget that you previously registered in the admin area.

Simplifying customization with functions

You may find that the simple Widget Area code doesn't accomplish all the functionality that you need. You may want to display a message on the website if a widget area is empty and doesn’t yet have any widgets added to it as a visual cue and reminder to add some widgets. A solution is to create a custom PHP function that gives you a few more options. Open functions.php, and insert the following code on a new blank line at the end of the file:

function add_new_widget_location($name) {
if (!function_exists('dynamic_sidebar') || ! dynamic_sidebar($name)) :?>
<div class="widget">
<h4><?php echo $name;?></h4>
<div class="widget">
<p>This section is widgetized. If you would like to
add content to this section, you may do so by using the Widgets
panel from within your WordPress Admin Dashboard. This Widget
Section is called "<strong><?php echo $name;?></strong>"</p>
</div>
</div>
<?php endif;?>
<?php
}

In this function, the first part checks whether a widget is assigned to this area. If so, the widget displays. If not, a message with the name of the widget area displays, which allows users to distinguish the widget area to which they need to add widgets in the Dashboard Widgets screen. Now if you want to display a widget by using this method, you go to the desired template file and insert the following code where you want the widget to appear in the sidebar.php or footer.php, as in this example:

<?php add_new_widget_location('Widget-Name');?>

Examining the Main Index and The Loop

At a bare minimum, a theme is required to have only two files. The first is style.css. The other is a main index file, known in WordPress as index.php. The index.php file is the first file WordPress tries to load when someone visits your site. Extremely flexible, index.php can be used as a stand-alone file, or it can include other templates. The Main Index template drags your content (posts, pages, categories, menus, and so on) out of the MySQL database and inserts them into your website for the whole world to see and read. This template is to your site what the dance floor is to a nightclub: It's where all the action happens.

The filename of the Main Index template is index.php. You can find it in the /wp-content/themes/twentynineteen/ folder.

The first template tag in the Main Index template calls in the Header template, meaning that it pulls the information from the Header template (header.php) into the Main Index template, as follows:

<?php get_header();?>

Your theme can work without calling in the Header template, but it will be missing several essential pieces: the CSS and the site name and tagline, for starters.

The Main Index template in the Twenty Nineteen theme connects with three other files in a similar fashion:

  • get_template_part('template-parts/content/content');: This function calls in the template file named content.php, located in the /twentynineteen/template-parts/content/ folder.
  • get_template_part('template-parts/content/content', 'none');: This function calls in the template file named content-none.php, located in the /twentynineteen/template-parts/content/ folder.
  • get_footer();: This function calls in the template file named footer.php.

I cover each of these three functions and template files in upcoming sections of this chapter.

Remember The concept of connecting with a template file by using a function or template tag is exactly what the Main Index template does with the four functions for the header, loop, sidebar, and footer templates, explained later in this section.

When I talk about The Loop, I'm not talking about America’s second-largest downtown business district, originating at the corner of State and Madison streets in Chicago. I could write about some interesting experiences I’ve had there … but that would be a different book.

The Loop, in this case, is a function that WordPress uses to display content on your site, such as blog posts and page content. The Loop has a starting point and an ending point; anything placed between those points is used to display each post, including any HTML, PHP, or CSS tags and codes.

Here’s a look at what the WordPress Codex calls the world’s simplest index page:

<?php
get_header();
if (have_posts()) :
while (have_posts()) :
the_post();
the_content();
endwhile;
endif;
get_sidebar();
get_footer();
?>

Here’s how the code works:

  1. The template opens the php tag.
  2. The Loop includes the header, meaning that it retrieves anything contained in the header.php file and displays it.
  3. The Loop begins with the while (have_posts()) : bit.
  4. Anything between the while and the endwhile repeats for each post that displays.

    The number of posts that displays is determined in the General Settings screen of the WordPress Dashboard.

  5. If your site has posts (and most do, even when you first install it), WordPress proceeds with The Loop, starting with the piece of code that looks like this:

    if (have_posts()) :
    while (have_posts()) :

    This code tells WordPress to grab the posts from the MySQL database and display them on your page.

  6. The Loop closes with these tags:

    endwhile;
    endif;

    Near the beginning of The Loop template is a template tag that looks like this:

    if (have_posts()) :

    In plain English, that tag says If [this blog] has posts.

  7. If your site meets that condition (that is, if it has posts), WordPress proceeds with The Loop and displays your posts. If it doesn't meet that condition (that is, doesn’t have posts), WordPress displays a message that no posts exist.
  8. When The Loop ends (at the endwhile), the index template goes on to execute the files for sidebar and footer.

Although it’s simple, The Loop is one of the core functions of WordPress.

Warning Misplacement of the while or endwhile statements causes The Loop to break. If you're having trouble with The Loop in an existing template, check your version against the original to see whether the while statements are misplaced.

Remember In your travels as a WordPress user, you may run across plugins or scripts with instructions that say something like this: “This must be placed within The Loop.” That’s The Loop that I discuss in this section, so pay particular attention. Understanding The Loop arms you with the knowledge you need to tackle and understand your WordPress themes.

The Loop is no different from any other template tag; it must begin with a function to start PHP, and it must end with a function to stop PHP. The Loop begins with PHP and then makes a request: “While there are posts in my site, display them on this page.” This PHP function tells WordPress to grab the post information from the database and return it to the page. The end of The Loop is like a traffic cop with a big red stop sign telling WordPress to stop the function.

Remember You can set the number of posts displayed per page in the Reading Settings screen of the WordPress Dashboard (choose Settings  ⇒  Reading). The Loop abides by this rule and displays only the number of posts per page that you’ve set.

WordPress uses other template files besides the main index, such as the header, sidebar, and footer templates. The next sections give you a closer look at a few of them.

Header template

The Header template for your WordPress themes is the starting point for every WordPress theme because it tells web browsers the following:

  • The title of your site
  • The location of the CSS
  • The RSS feed URL
  • The site URL
  • The tagline (or description) of the website

In many themes, the first elements in the header are a main image and the navigation. These two elements are usually in the header.php file because they load on every page and rarely change. The following statement is the built-in WordPress function to call the header template:

<?php get_header();?>

Tip Every page on the web has to start with a few pieces of code. In every header.php file in any WordPress theme, you can find these bits of code at the top:

  • The DOCTYPE (which stands for document type declaration) tells the browser which type of XHTML standards you're using. The Twenty Nineteen theme uses <!DOCTYPE html>, which is a declaration for W3C standards compliance mode and covers all major browsers.
  • The <html> tag (HTML stands for Hypertext Markup Language) tells the browser which language you're using to write your web pages.
  • The <head> tag tells the browser that the information contained within the tag shouldn’t be displayed on the site; rather, it’s information about the document.

In the Header template of the Twenty Nineteen theme, these bits of code look like the following example, and you should leave them intact:

<!DOCTYPE html>
<html <?php language_attributes();?>>
<head>

Tip On the Edit Themes screen of the Dashboard (choose Appearance  ⇒  Editor), click the Header template link to display the template code in the text box. Look closely, and you see that the <!DOCTYPE html> declaration, <html> tag, and <head> tag show up in the template.

The <head> tag needs to be closed at the end of the Header template, which looks like this: </head>. You also need to include a fourth tag, the <body> tag, which tells the browser where the information you want to display begins. Both the <body> and <html> tags need to be closed at the end of the template, like this: </body></html>.

Using bloginfo parameters

The Header template makes much use of one WordPress template tag in particular: bloginfo();. It's commonly used in WordPress themes.

What differentiates the type of information that a tag pulls in is a parameter. Parameters are placed inside the parentheses of the tag, enclosed in single quotes. For the most part, these parameters pull information from the settings in your WordPress Dashboard. The template tag to get your site title, for example, looks like this:

<?php bloginfo('name');?>

Table 3-2 lists the various parameters you need for the bloginfo(); tag and shows you what the template tag looks like. The parameters in Table 3-2 are listed in the order of their appearance in the Twenty Nineteen header.php template file and in the /template-parts/header/site-branding.php file, and they pertain only to the bloginfo(); template tag.

TABLE 3-2 Tag Values for bloginfo();

Parameter

Information

Tag

charset

Character settings, set in the General Settings screen

<?php bloginfo('charset');?>

name

Site title, set by choosing Settings  ⇒  General

<?php bloginfo('name');?>

description

Tagline for your site, set by choosing Settings  ⇒  General

<?php bloginfo('description');?>

url

Your site's web address, set by choosing Settings  ⇒  General

<?php bloginfo('url');?>

stylesheet_url

URL of primary CSS file

<?php bloginfo('stylesheet_url');?>

pingback_url

Displays the trackback URL for your site on single post pages

<?php bloginfo('pingback_url');?>

Remember Although the Twenty Nineteen theme breaks the header information into two template files, most WordPress themes have this bloginfo(); information only in the header.php file. The placement of the bloginfo(); tag varies from theme to theme.

Creating <title> tags

Here's a useful tip about your site’s <title> tag: Search engines pick up the words used in the <title> tag as keywords to categorize your site in their directories. The <title>…</title> tags are HTML tags that tell the browser to display the title of your website on the title bar of a visitor's browser.

Remember Search engines love the title bar. The more you can tweak that title to provide detailed descriptions of your site (otherwise known as search engine optimization, or SEO), the more the search engines love your web site. Browsers show that love by giving your site higher rankings in their results.

The site <title> tag is the code that lives in the Header template between these two tag markers: <title></title>. In the default Twenty Nineteen theme, that bit of code (located in the theme's functions.php template file) looks like this:

add_theme_support('title-tag');

The add_theme_support('title-tag'); in the functions.php template tells WordPress to place the title tag in the <head> section of the website. By adding theme support for the title tag, you're saying that this theme doesn’t use a hard-coded <title> tag in the document head and that you expect WordPress to provide it.

The way that the add_theme_support('title-tag'); function displays the title is based on the type of page that's being displayed, and it shrewdly uses SEO to help you with the browser powers that be.

Within some of the WordPress template tags, such as the <title> tag example at the beginning of this section, you may notice some weird characters that look like a foreign language. You may wonder what &raquo; is, for example. It isn't part of any PHP function or CSS style. Rather, it’s a character entity — a kind of code that enables you to display a special character in your blog. The &raquo; character entity displays a double right-angle quotation mark.

Displaying your blog name and tagline

Most WordPress themes show your site name and tagline in the header of the site, which means that those items are displayed in easy, readable text for all visitors (not just search engines) to see. My site name and tagline, for example, are

  • Site name: Lisa Sabin-Wilson
  • Site tagline: Author of WordPress For Dummies and owner of WebDevStudios

You can use the bloginfo(); tag plus a little HTML code to display your site name and tagline. Most sites have a clickable title, which is a site title that takes you back to the main page when it's clicked. No matter where your visitors are on your site, they can always go back home by clicking the title of your site on the header.

To create a clickable title, use the following HTML markup and WordPress template tags:

<a href="<?php bloginfo('url');?>"><?php bloginfo('name');?></a>

The bloginfo(‘url’); tag is your main site Internet address, and the bloginfo('name’); tag is the name of your site (refer to Table 3-1). So the code creates a link that looks something like this:

<a href="http://yourdomain.com">Your Site Name</a>

The tagline generally isn’t linked back home. You can display it by using the following tag:

<?php bloginfo('description');?>

This tag pulls the tagline directly from the one that you’ve set up on the General Settings screen of your WordPress Dashboard.

This example shows that WordPress is intuitive and user-friendly; you can do things such as change the site name and tagline with a few keystrokes on the Dashboard. Changing your options in the Dashboard creates the change on every page of your site; no coding experience is required. Beautiful, isn’t it?

In the Twenty Nineteen templates, these tags are surrounded by tags that look like these: <h1></h1> or <p></p>. These tags are Header and Paragraph tags, which define the look and layout of the site name and tagline in the CSS of your theme. Book 6, Chapter 4 covers CSS.

Sidebar template

The Sidebar template in WordPress has the filename sidebar.php. The sidebar usually appears on the left or right side of the main content area of your WordPress theme. (The default Twenty Nineteen theme doesn't have a sidebar by design.) It’s a good place to put useful information about your site, such as a site summary, advertisements, or testimonials.

Many themes use widget areas in the sidebar template to display content on WordPress pages and posts. The following line of code is the built-in WordPress function that calls the Sidebar template:

<?php get_sidebar();?>

This code calls the Sidebar template and all the information it contains into your page.

Footer template

The Footer template in WordPress has the filename footer.php. The footer is generally at the bottom of the page and contains brief reference information about the site, usually including copyright information, template design credits, and a mention of WordPress. Similar to the Header and Sidebar templates, the Footer template gets called into the Main Index template through this bit of code:

<?php get_footer();?>

Tip You can write calls for the Sidebar and Footer templates that are written as part of a larger call:

<?php
get_sidebar();
get_footer();
?>

It’s possible, and common, to wrap two template tags in one PHP function that way if they appear directly after one another. The examples I give in this chapter separate them into single functions to make sure that you’re clear about what the actual function is.

This code calls the Footer and all the information it contains into your website page.

Examining Other Template Files

To make your website work properly, WordPress uses all the theme files together. Some, such as the header and footer, are used on every page. Others, such as the Comments template (comments.php), are used only at specific times, to pull in specific functions.

When someone visits your site, WordPress uses a series of queries to determine which templates to use.

You can include many more theme templates in your theme. Here are some of the other template files you may want to use:

  • Comments template (comments.php): The Comments template is required if you plan to host comments on your site; it provides all the template tags you need to display those comments. The template tag used to call the comments into the template is <?php comments_template();?>.
  • Single Post template (single.php): When your visitors click the title or permalink of a post you published to your site, they're taken to that post’s individual page. There, they can read the entire post, and if you have comments enabled, they see the comments form and can leave comments.
  • Page template (page.php): You can use a Page template for static pages of your WordPress site.
  • Search Results (search.php): You can use this template to create a custom display of search results on your blog. When someone uses the search feature to search your site for specific keywords, this template formats the return of those results.
  • 404 template (404.php): Use this template to create a custom 404 page, which is the page visitors get when the browser can't find the page requested and returns that ugly 404 Page Cannot Be Found error.

Remember The templates in the preceding list are optional. If these templates don't exist in your WordPress themes folder, nothing breaks. The Main Index template handles the display of these items (the single post page, the search results page, and so on). The only exception is the Comments template. If you want to display comments on your site, you must include that template in your theme.

Customizing Your Posts with Template Tags

This section covers the template tags that you use to display the body of each post you publish. The body of a post includes information such as the post date and time, title, author name, category, and content.

Table 3-3 lists the common template tags you can use for posts, available for you to use in any WordPress theme template. The tags in Table 3-3 work only if you place them within The Loop (covered in “Examining the Main Index and The Loop” earlier in this chapter).

TABLE 3-3 Template Tags for Posts

Tag

Function

get_the_date();

Displays the date of the post.

get_the_time();

Displays the time of the post.

the_title();

Displays the title of the post.

the_permalink();

Displays the permalink (URL) of the post.

get_the_author();

Displays the post author's name.

the_author_link();

Displays the URL of the post author's site.

the_content(‘Read More…’);

Displays the content of the post. (If you use an excerpt [following], the words Read More appear and are linked to the individual post page.)

the_excerpt();

Displays an excerpt (snippet) of the post.

the_category();

Displays the category (or categories) assigned to the post. If the post is assigned to multiple categories, commas separate them.

comments_popup_link('No Comments', 'Comment (1)', 'Comments(%)');

Displays a link to the comments, along with the comment count for the post in parentheses. (If no comments exist, it displays a No Comments message.)

next_posts_link('&laquo; Previous Entries')

Displays the words Previous Entries linked to the previous page of blog entries.

previous_posts_link('Next Entries &raquo;')

Displays the words Next Entries linked to the next page of blog entries.

The last two tags in Table 3-3 aren't like the others. You don’t place these tags in The Loop; instead, you insert them after The Loop but before the if statement ends. Here’s an example:

<?php endwhile;?>
<?php next_posts_link('« Previous Entries');?>
<?php previous_posts_link('Next Entries »');?>
<?php endif;?>

Putting a Theme Together

The template files don’t work alone; for the theme to function, the files need one another. To tie these files together as one working entity, you use template tags to pull the information from each template — Header, Sidebar, and Footer — into the Main Index. I refer to this procedure as calling one template into another.

Connecting the templates

WordPress has built-in functions to include the main template files, such as header.php, sidebar.php, and footer.php, in other templates. An include function is a custom PHP function that is built into WordPress, allowing you to retrieve the content of another template file and display it along with the content of another template file. Table 3-4 shows the templates and the function that include them.

TABLE 3-4 Template Files and Include Functions

Template Name

Include Function

header.php

<?php get_header();?>

sidebar.php

<?php get_sidebar();?>

footer.php

<?php get_footer();?>

search.php

<?php get_search_form();?>

comments.php

<?php comments_template();?>

If you want to include a file that doesn't have a built-in include function, you need a different piece of code. To add a unique sidebar (different from the default sidebar.php file within your existing theme) to a certain page template, name the sidebar file sidebar-page.php. To include it in another template, use the following code:

<?php get_template_part('sidebar', 'page');?>

In this statement, the get_template_part('sidebar', 'page'); function looks through the main theme folder for the sidebar-page.php file and displays the sidebar. The beautiful part about the get template part() template tag is that WordPress looks for the sidebar-page.php template first, but if it doesn't find that template, it defaults to using the sidebar.php template.

In this section, you put together the guts of a basic Main Index template by using the information on templates and tags from this chapter. There seem to be endless lines of code when you view the template files in the Twenty Nineteen theme, so I’ve simplified the file for you in a list of steps. These steps should give you a basic understanding of the WordPress Loop and common template tags and functions that you can use to create your own.

Warning The theme you’re creating in this chapter won’t win you any awards. In fact, it’s pretty ugly, as you’ll see when you activate it on your website. It doesn’t have many of the features that you expect from a WordPress theme, it’s not responsive on mobile devices, and so on. The intention for the creation of the theme in this chapter is to get you comfortable with the basic concepts and mechanics of themes, including using the template tags that make themes work and understanding how to put different templates together. I didn’t want to complicate this theme for beginners. Take the concepts you learn here and apply them as you move forward with more advanced theme development — and please don’t use this theme anywhere on the web.

You create a new WordPress theme by using some of the basic WordPress templates. The first steps in pulling everything together are as follows:

  1. Connect to your web server via SFTP, click the wp-content folder, and then click the themes folder.

    This folder contains the themes that are currently installed in your WordPress site. (See Book 2, Chapter 2 for more information on SFTP.)

  2. Create a new folder, and call it my-theme.

    In most SFTP programs, you can right-click in the window and choose New Folder from the shortcut menu. (If you aren't sure how to create a folder, refer to your SFTP program’s help files.)

  3. In your favored text editor (such as Notepad for the PC or TextEdit for the Mac), create and save the following files with the lines of code I’ve provided for each:
    • Header template: Create the file with the following lines of code and then save it with the filename header.php:

      <!DOCTYPE html>
      <html <?php language_attributes();?>>
      <head>
      <meta charset="<?php bloginfo('charset');?>">
      <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo('stylesheet_url');?>"/>
      <?php wp_head();?>
      </head>
      <body <?php body_class()?>>
      <header class="masthead">
      <h1><a href="<?php bloginfo('url');?>"><?php bloginfo('name');?></a></h1>
      <h2><?php bloginfo('description');?></h2>
      </header>
      <div id="main">

    • Theme Functions: Create the file with the following lines of code and then save it, using the filename functions.php:

      <?php

      add_theme_support('title-tag');

      function my_widgets_init() {
      register_sidebar(array (
      'name' => __('My Widget Area'),
      'id' => 'my-widget-area',
      'description' => __('A new widget area I created!'),
      'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
      'after_widget' => "</li>",
      'before_title' => '<h3 class="widget-title">',
      'after_title' => '</h3>',
      ));
      }
      add_action('widgets_init', 'my_widgets_init');

      The Theme Functions file registers the widget area for your site so that you can add widgets to your sidebar by using the WordPress widgets available on the Widget page of the Dashboard.

    • Sidebar template: Create the file with the following lines of code and then save it, using the filename sidebar.php:

      <aside class="sidebar">
      <ul>
      <?php dynamic_sidebar('My Widget Area');?>
      </ul>
      </aside>

      The code here tells WordPress where you want the WordPress widgets to display in your theme; in this case, widgets are displayed on the sidebar of your site.

    • Footer template: Create the file with the following lines of code and then save it with the filename footer.php:

      <footer>
      <p>© Copyright <a href="<?php bloginfo('url');?>"><?php bloginfo('name');?></a>. All Rights Reserved</p>
      </footer>
      <?php wp_footer();?>
      </body>
      </html>

    • Stylesheet: Create the file with the following lines of code and then save it with the filename style.css:

      /*
      Theme Name: My Theme
      Description: Basic Theme from WordPress For Dummies example
      Author: Lisa Sabin-Wilson
      Author URI: http://lisasabin-wilson.com
      */

      body {
      color: #333333;
      font-family: verdana, arial, helvetica, sans-serif;
      font-size: 18px;
      }

      header.masthead {
      background: black;
      color: white;
      margin: 0 auto;
      padding: 15px;
      text-align:center;
      width: 960px;
      }

      header.masthead h1 a {
      color: white;
      font-family: Georgia;
      font-size: 28px;
      text-decoration: none;
      }

      header.masthead h2 {
      color: #eee;
      font-family: Georgia;
      font-size: 16px;
      }

      #main {
      margin: 0 auto;
      padding: 20px ;
      width: 960px;
      }

      #main section {
      float:left;
      width: 500px;
      }

      #main .hentry {
      margin: 10px 0;
      }

      aside.sidebar {
      float:right;
      margin: 0 15px;
      width: 290px;
      }

      aside.sidebar ul {
      list-style:none;
      }

      footer {
      background: black;
      clear:both;
      color: white;
      height: 50px;
      margin: 0 auto;
      width: 960px;
      }

      footer p {
      padding: 15px 0;
      text-align:center;
      }

      footer a {
      color:white;
      }

Using the tags provided in Table 3-3, along with the information on The Loop and the calls to the Header, Sidebar, and Footer templates provided in earlier sections, you can follow the next steps for a bare-bones example of what the Main Index template looks like when you put the tags together.

Warning When typing templates, be sure to use a text editor such as Notepad or TextEdit. Using a word processing program such as Microsoft Word opens a whole slew of problems in your code. Word processing programs insert hidden characters and format quotation marks in a way that WordPress can't read.

Now that you have the basic theme foundation, the last template file you need to create is the Main Index template. To create a Main Index template to work with the other templates in your WordPress theme, open a new window in a text-editor program and then follow these steps. (Type the text in each of these steps on its own line. Press the Enter key after typing each line so that each tag starts on a new line.)

  1. Type <?php get_header();?>.

    This template tag pulls the information in the Header template of your WordPress theme.

  2. Type <section>.

    This HTML5 markup tells the browser that this tag is a grouping of content (in this case, blog posts).

  3. Type <?php if (have_posts()) :?>.

    This tag is an if statement that asks, “Does this blog have posts?” If the answer is yes, the tag grabs the post content information from your MySQL database and displays the posts in your blog.

  4. Type <?php while (have_posts()) : the_post();?>.

    This template tag starts The Loop.

  5. Type <article <?php post_class()?> id="post-<?php the_ID();?>">.

    This tag is HTML5 markup that tells the browser that the tag, <article>, is the start of a new single article, including the post_class CSS designation.

  6. Type <h1><a href="<?php the_permalink();?>"><?php the_title();?></a></h1>.

    This tag tells your blog to display the title of a post that's clickable (linked) to the URL of the post, surrounded by HTML Header tags.

  7. Type Posted on <?php the_date();?> at <?php the_time();?>.

    This template tag displays the date and time when the post was made. With these template tags, the date and time format are determined by the format you set on the Dashboard.

  8. Type Posted in <?php the_category( ',' );?>.

    This template tag displays a comma-separated list of the categories to which you've assigned the post, such as Posted in: category 1, category 2, for example.

  9. Type <?php the_content('Read More..');?>.

    This template tag displays the actual content of the blog post. The 'Read More..' portion of this tag tells WordPress to display the words Read More, which are hyperlinked to the post's permalink and take the reader to the page where he or she can read the rest of the post. This tag applies when you’re displaying a post excerpt, as determined by the actual post configuration on the Dashboard.

  10. Type Posted by: <?php the_author();?>.

    This template tag displays the author of the post in this manner: Posted by: Lisa Sabin-Wilson.

  11. Type </article>.

    This tag is HTML5 markup that tells the browser that the article has ended.

  12. Type <?php endwhile;?>.

    This template tag ends The Loop and tells WordPress to stop displaying blog posts here. WordPress knows exactly how many times The Loop needs to work, based on the setting on the WordPress Dashboard. That setting is exactly how many times WordPress executes The Loop.

  13. Type <?php next_posts_link('&laquo; Previous Entries');?>.

    This template tag displays a clickable link that goes to the preceding page of entries, if any.

  14. Type <?php previous posts link('&raquo; Next Entries');?>.

    This template tag displays a clickable link that goes to the next page of blog entries, if any.

  15. Type <?php else :?>.

    This template tag refers to the if statement in step 3. If the answer is no, this step provides the else statement: IF this blog has posts, THEN list them here (steps 3 and 4), or ELSE display the following message.

  16. Type Not Found. Sorry, but you are looking for something that isn't here.

    This tag is the message followed by the template tag displayed after the else statement from step 15. You can reword this statement to say whatever you want.

  17. Type <?php endif;?>.

    This template tag ends the if statement from step 3.

  18. Type </section>.

    This HTML5 markup closes the <section> tag that was opened in step 2 and tells the browser that this grouping of content has ended.

  19. Type <?php get_sidebar();?>.

    This template tag calls in the Sidebar template and pulls that information into the Main Index template.

  20. Type </div>.

    This HTML5 markup closes the <div id="main"> that was opened in the header.php file.

  21. Type <?php get_footer();?>.

    This template tag calls in the Footer template and pulls that information into the Main Index template. Note: The code in the footer.php template ends the <body> and <html> tags that were started in the Header template (header.php).

    When you're done, the display of the Main Index template code looks like this:

    <?php get_header();?>
    <section>
    <?php if (have_posts()) :?>

    <?php while (have_posts()) : the_post();?>
    <article <?php post_class()?> id="post-<?php the_ID();?>">
    <h1><a href="<?php the_permalink();?>"><?php the_title();?></a></h1>
    Posted on: <?php the_date();?> at <?php the_time();?>
    Posted in: <?php the_category( ',' );?>
    <?php the_content('Read More..');?>
    Posted by: <?php the_author();?>
    </article>

    <?php endwhile;?>
    <?php next_posts_link('« Previous Entries');?>
    <?php previous_posts_link('Next Entries »');?>
    <?php else :?>

    <p>Not Found
    Sorry, but you are looking for something that isn't here.</p>
    <?php endif;?>
    </section>
    <?php get_sidebar();?>
    </div>
    <?php get_footer();?>

  22. Save this file as index.php, and upload it to the mythemes folder.

    In Notepad or TextEdit, you can save the PHP file by choosing File  ⇒  Save As. Type the name of the file in the File Name text box, and click Save.

  23. Activate the theme on the WordPress Dashboard, and view your site to see your handiwork in action!

Tip This Main Index template code has one template tag that's explained in Book 6, Chapter 6: <div <?php post_class()?> id="post-<?php the_ID();?>">. This tag helps you create some interesting styles in your template by using CSS, so check out Chapter 6 to find out all about it!

This simple, basic Main Index template doesn’t have the standard HTML markup in it, so you’ll find that the visual display of your site differs from the default Twenty Nineteen theme. I use this example to give you bare-bones basics on the Main Index template and The Loop in action. Book 6, Chapter 4 goes into detail about using HTML and CSS to create nice styling and formatting for your posts and pages.

Tip If you’re having a hard time typing the code provided in this section, I’ve made this sample theme available for download on my website. The .zip file contains the files discussed in this chapter so that you can compare your efforts with mine, electronically. You can download the file here: http://lisasabin-wilson.com/wpfd/my-theme.zip.

Now that you have all your template files ready, follow these steps to upload your files to your web server:

  1. Connect to your web server via SFTP, click the wp-content folder, and then click the themes folder.

    This folder contains the themes that are currently installed in your WordPress blog. (Go to Book 2, Chapter 2 if you need more information on SFTP.)

  2. Create a new folder, and call it my-theme.

    In most SFTP programs, you can right-click and choose New Folder from the shortcut menu. (If you aren't sure how to create a folder, refer to your SFTP program’s help files.)

  3. Upload your index.php file to the my-theme folder.
  4. Activate the theme in the WordPress Dashboard, and view your site to see your handiwork in action.

Using additional stylesheets

Often, a theme uses multiple stylesheets for browser compatibility or consistent organization. If you use multiple stylesheets, the process of including them in the template is the same as for any other stylesheet.

To add a new stylesheet, create a directory in the root theme folder called css. Next, create a new file called mystyle.css within the css folder. To include the file, you must edit the header.php file. The following example shows the code you need to include in the new CSS file:

<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory');
?>/css/mystyle.css" type="text/css" media="screen"/>

Additional stylesheets come in handy when you’re working with a concept called parent and child themes, which is the practice of creating a child theme that depends on a separate parent theme for features and functions. I write more about parent and child themes, as well as provide additional information about HTML and CSS, in Book 6, Chapter 5.