Chapter 9

Understanding Themes and Templates

In This Chapter

arrow Looking at the basic website structure

arrow Exploring the required templates

arrow Understanding The Loop and Main Index template

arrow Putting together a basic theme

arrow Using common template tags

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: You can have 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 websites will have the same look as yours.)
  • Creativity: You can display your own personal flair and style.
  • Control: You can have full control of how the site looks, acts, and delivers your content.

Many of you aren’t at all interested in creating your own theme for your WordPress blog, however. Sometimes, it’s just 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 Chapter 8). Chapter 16 also tells you where you can get ten free WordPress themes.

Creating themes requires you to step into the code of the templates, which can be a scary place sometimes — especially if you don’t really 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 to put 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 HTML 4 For Dummies, 5th Edition, by Ed Tittel and Mary Burmeister, or HTML, XHTML, and CSS Bible, 5th Edition, by Steven M. Schafer (both published by John Wiley & Sons, Inc.).

Using WordPress Themes: 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. WordPress template tags make all the templates work together as a theme (more about this topic in the “Examining the Anatomy of a Template Tag” section, later in this chapter).

Understanding theme structure

The rest of this chapter provides important information about the steps to building a WordPress theme, but here is an overview of the templates that make up a WordPress theme and where you find them, both on your server and within your WordPress Dashboard. Follow these steps:

  1. Connect to your web server via FTP and have a look at the existing WordPress themes on your server.

    The correct location is /wp-content/themes/ (see the right side of Figure 9-1). When you open this folder, you find the /twentyfifteen theme folder.

    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 Fifteen theme (/wp-content/themes/twentyfifteen ) and look at the template files inside.

    When you open the Twenty Fifteen theme folder, you see several files. At minimum, you find these five templates in the default theme:

    • Stylesheet (style.css)
    • Header template (header.php)
    • Main Index (index.php)
    • Sidebar template (sidebar.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 other template files, however, and you should try to explore them all if you can. Take a peek inside and see the different template functions they contain. These filenames are the same in every WordPress theme. See the “Contemplating the Structure of a WordPress Website” section later in this chapter for more information about these template files.

  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 9-2 shows the templates in the default Twenty Fifteen theme.) A text box on the left side 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 name in the list on the right side of the page.

image

Figure 9-1: WordPress themes in the /wp-content/themes folder in FTP.

image

Figure 9-2: A list of templates available in the default Twenty Fifteen WordPress theme.

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

tip Below the text box on the Edit Themes page is a drop-down menu labeled Documentation. Click the arrow on the right side of the menu, and a list drops down that contains all of the template tags used in the template you’re currently viewing. This list is helpful when you edit templates and it gives you some insight into some of the different template tags used to create functions and features within your WordPress theme. ( Note: The Documentation menu does not appear when you view the Stylesheet because no template tags are used in the style.css template — only CSS, which I cover in Chapter 10.)

Connecting templates

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. (You can find more information in the “Getting Familiar with the Four Main Templates” section later in this chapter.)

Contemplating the Structure of a WordPress Website

A WordPress blog, in its very basic form, has four main areas (labeled in Figure 9-3).

image

Figure 9-3: The four main sections of a WordPress blog.

These four main areas appear in the default theme that comes in every version of WordPress:

  • Header: This area usually contains the name of the site along with the site tagline or slogan. Sometimes the header also contains a graphic or image.
  • Body: This area is where the main content of your website appears; for example, blog posts displayed in chronological order.
  • Sidebar: This area is where you find lists of blog-related elements, such as the blogroll, the archives, and a list of recent posts.
  • Footer: This area, at the bottom of the page, often contains links to further information about the website, such as who designed it, which company provides hosting for the site, and copyright information.

These four areas are the absolute bare bones of a basic WordPress blog template. You can extend these areas and create new sections that carry more information, of course, but for the purpose of this chapter, I’m focusing on the basics.

The default WordPress theme is called Twenty Fifteen, and in my opinion, it’s a pretty doggone wonderful starting point for you, especially if you’re just getting your feet wet in web publishing. I don’t cover all the tags and templates that the Twenty Fifteen theme includes; rather, I touch on the basics to get you on your way to understanding templates and template tags for WordPress.

tip Many themes developed for WordPress are free for public use, and I strongly recommend finding one that you like and downloading it. Use the free themes as a jumping-off place to get started in theme development. Really, why reinvent the wheel? With the free themes available today, most of the work has already been completed for you, and you may find it easier to use one of these themes than to start a theme from scratch.

Each free theme available for download is different, depending on what the developer included (such as CSS styling, display options, format, and layout). So experimenting with a few themes is a fun and great way to learn more about the development of WordPress themes. A great place to find free WordPress themes is the official WordPress Themes Directory at https://wordpress.org/themes.

To build a basic WordPress theme that covers the four basic areas of a website, you need these five templates:

  • header.php
  • index.php
  • sidebar.php
  • footer.php
  • style.css

Each WordPress theme comes with a stylesheet (style.css), which drives the formatting and layout of your blog template in terms of where the elements are positioned on the page, what the font looks like, what colors your hyperlinks will be, and so on. As you may have already figured out, you don’t use CSS to put content on your site; rather, you use CSS to style the content that’s already there.

Chapter 10 provides information on tweaking the design of your theme by combining the template tags presented in this chapter with some CSS adjustments in your theme files.

Right now, I’m covering only the very basics; at the end of this chapter, however, I provide some ideas on how you can use various templates to further extend your website functionality — using templates for categories, archives, static pages, multiple sidebars, and so on. After you build the basics, you can spread your wings and step into more advanced themes.

Examining the Anatomy of a Template Tag

Before starting to play around with template tags in your WordPress templates, 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 the function to start PHP and ends with the 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 get_info(); ?>

This entire 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 (get_info();).
  • Stop PHP (?>).

In this case, get_info represents the tag function, which grabs information from the database to deliver it to your site. What information is retrieved depends on what tag function appears between the two PHP commands. As you may notice, a lot of starting and stopping of PHP happens 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.

Getting Familiar with the Four Main Templates

In the following sections, I cover some of the template tags that pull in the information you want to include in your website. To keep this chapter shorter than 1,000 pages, I focus on the four main templates that get you going with creating your own theme or with editing the template tags in the theme you’re currently using. Here are those four main templates:

  • Header
  • Main Index
  • Sidebar
  • Footer

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 appears. A theme is a set of templates. The theme uses the templates to make the whole site.

The Header template

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

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

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 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 Fifteen theme uses <!DOCTYPE html>, which is a declaration for W3C standards compliance mode and covers all major browser systems.
  • 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, that information is about the document.

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

<!DOCTYPE html>

<html <?php language_attributes(); ?> class="no-js">

<head>

tip On the Edit Themes page, 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, and the closing tag 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 files (in the footer.php), like this: </body></html>.

Using bloginfo parameters

The Header template makes much use of one WordPress template tag in particular: bloginfo();.

A parameter differentiates the type of information that a tag pulls in. 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 9-1 lists the various parameters you need for the bloginfo(); tag and shows you what the template tag looks like. The parameters in Table 9-1 are commonly used in the header.php template file in many WordPress themes and pertain to the bloginfo(); template tag only.

Table 9-1 Tag Values for bloginfo(); Commonly Used in WordPress Themes

Parameter

Information

Tag

charset

Character settings, set in Settings/General

<?php bloginfo( ‘charset’ ); ?>

name

Site title, set in Settings/General

<?php bloginfo( ‘name’ ); ?>

description

Tagline for your site, set in Settings/General

<?php bloginfo( ‘description’ ); ?>

url

Your site’s web address, set in 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’ ); ?>

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 search engine directories.

The <title></title> tags are HTML tags that tell the browser to display the title of your website in the title bar of a visitor’s browser. Figure 9-4 shows how the title of my personal blog sits in the title bar of the browser window. The title bar is the top bar in your browser. In Figure 9-4, it says Lisa Sabin-Wilson — Designer, Author: WordPress For Dummies.

image

Figure 9-4: The title bar of a 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 blog site. Browsers show that love by giving your site higher rankings in their results.

The blog <title> tag is the code that lives in the Header template between these two tag markers: <title></title>. In the default Twenty Fifteen theme, this bit of code looks like this, and is found in the functions.php template file of the theme:

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.

It may help for me to put this example into plain English. The way 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.

remember The title bar of the browser window always displays your site name unless you’re on a single post page. In that case, it shows your site title plus the title of the post on that page.

Displaying your site name and tagline

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

  • Site name: Lisa Sabin-Wilson
  • Site tagline: Designer, Author: WordPress For Dummies

Refer to Figure 9-4 to see these two elements in the header of the site.

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 clicked. No matter where your visitors are on your site, they can always go back home by clicking the title of your site in 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 9-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 page in your WordPress Dashboard.

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

In the default Twenty Fifteen templates, these tags are surrounded by tags that look like these: <h1></h1> or <p></p>. These tags are HTML markup tags, which define the look and layout of the blog name and tagline in the CSS of your theme. I cover CSS further in Chapter 10.

The header.php template file also includes the sidebar.php template file, which means it tells WordPress to execute and display all of the template functions included in the Sidebar template (sidebar.php). The line of code from the Header template that does this looks like this:

get_sidebar();

I cover more about including other templates by calling them in through the use of template functions in the next sections of this chapter.

The Main Index template

The Main Index template drags your blog posts out of the MySQL database and inserts them into your site. This template is to your blog what the dance floor is to a nightclub — where all the action happens.

The filename of the Main Index template is index.php. In the default Twenty Fifteen theme, you can find it in the /wp-content/themes/twentyfifteen/ 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 into the Main Index template, as follows:

<?php get_header(); ?>

Your theme can work without calling in the Header template, but it’ll be missing several essential pieces — the CSS and the blog name and tagline, for starters. Without the call to the Header template, your blog resembles the image shown in Figure 9-5.

image

Figure 9-5: A WordPress blog missing the call to the header. It’s naked!

The Main Index template in the default theme, Twenty Fifteen, calls in two other files in a similar fashion:

  • get_template_part( 'content', 'get_post_format' );: This function calls in the template file named content.php as well as prepares the theme to accept special templates for a feature called Post Formats, which I cover in Chapter 12.
  • get_footer();: This function calls in the template file named footer.php.

Each of these two functions and template files is covered in upcoming sections of this chapter.

remember Earlier in this chapter, in the “Connecting templates” section, I explain the concept of calling in a template file using a function or template tag. That is exactly what the Main Index template does with the four functions for the Header, Loop, Sidebar, and Footer templates explained in this section.

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 in between is used to display each post, including any HTML, PHP, or CSS tags and codes.

Quite a few variations of the WordPress Loop are available, but I cover the most common use in this section. When you understand the common use, you can begin to push the envelope a bit further and use variations to suit your needs. This common use displays your posts in chronological order, starting with your most recent post and followed by less recent posts, ordered by date.

The basic and most common use of The Loop in WordPress is to pull blog posts from the database and display them on your website. In the default Twenty Fifteen theme, you find the loop in the Main Index template (index.php) and it contains these four lines of code:

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

<?php

// Start the Loop.

while ( have_posts() ) : the_post();

At the bottom of the template, The Loop ends with these lines of code:

endwhile;

endif;

Here’s a look at what the WordPress Codex calls “The World’s Simplest Index”:

<?php

get_header();

if (have_posts()) :

   while (have_posts()) :

      the_post();

      the_content();

   endwhile;

endif;

get_sidebar();

get_footer();

?>

First, the template starts by opening the php tag. Next, it includes the header, meaning that it retrieves anything contained in the header.php file and displays it. Now the good stuff starts happening. The Loop begins with the while (have_posts()) : bit. Anything between the while and the endwhile repeats for each post that displays. The number of posts displayed is determined in the settings section of the WordPress Dashboard.

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 and 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 we discuss in this section, so pay particular attention. Understanding The Loop arms you with the knowledge you need for tackling and understanding 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 blog, display them on this page.” This PHP function tells WordPress to grab the blog post information from the database and return it to the blog page. The end of The Loop is like a traffic cop with a big red stop sign telling WordPress to stop the function completely.

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

The big if

PHP functions in a pretty simple, logical manner. It functions by doing what you and I do on a daily basis — making decisions based on questions and answers. PHP deals with three basic variables:

  • if
  • then
  • else

The basic idea is this: IF this, THEN that, or ELSE this.

If your blog 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:

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

This code tells WordPress to grab the posts from the MySQL database and display them on your blog page. Then The Loop closes with this tag:

<?php endwhile; ?>

In some themes, near the beginning of The Loop template you may see a template tag that looks like this:

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

The exclamation point (!) preceding the function: have_posts() means “does not.” So a translation of that template tag into plain English reads: If [this blog] does not have posts.

In the Twenty Fifteen theme, your blog meets that condition (that is, if it doesn’t have any posts), WordPress skips The Loop and displays a message that no posts exist by calling in the content-none.php template part:

<section class="no-results not-found">

<header class="page-header">

<h1 class="page-title"><?php _e( ‘Nothing Found’, ‘twentyfifteen’ ); ?></h1>

</header><!-- .page-header -->

<div class="page-content">

<?php if ( is_home() && current_user_can( ‘publish_posts’ ) ) : ?>

<p><?php printf( __( ‘Ready to publish your first post? <a href="%1$s">Get started here</a>.’, ‘twentyfifteen’ ), esc_url( admin_url( ‘post-new.php’ ) ) ); ?></p>

<?php elseif ( is_search() ) : ?>

<p><?php _e( ‘Sorry, but nothing matched your search terms. Please try again with some different keywords.’, ‘twentyfifteen’ ); ?></p>

<?php get_search_form(); ?>

<?php else : ?>

<p><?php _e( ‘It seems we can't find what you're looking for. Perhaps searching can help.’, ‘twentyfifteen’ ); ?></p>

<?php get_search_form(); ?>

<?php endif; ?>

</div><!-- .page-content -->

</section><!-- .no-results -->

WordPress displays the title Nothing Found, followed by a text statement for the visitor, depending on some factors that are seen in the if or else statements in the code snippet above:

  • <?php if ( is_home() && current_user_can( ‘publish_posts’ ) ) : ?>: This statement says that if you are viewing the home page and you are currently logged in as a user who has the capability to publish posts on the site, then display the following text: Ready to publish your first post? Get started here.
  • <?php elseif ( is_search() ) : ?>: This statement says that if the visitor is on a search page, then display the following statement: Sorry, but nothing matched your search terms, please try again with some different keywords. This statement is followed by the template tag to include a searchbox that allows users to search the site for more information: <?php get_search_form(); ?>.
  • <?php else : ?>: This statement says that if the visitor is visiting a page that does not meet any of the above two conditions, then display the following statement: It seems we can't find what you're looking for. Perhaps searching can help. The template tag to include the search form, as in the previous example, follows this statement.

technicalstuff Mixed within the template tags and functions explained in these sections of this chapter, you find basic HTML markup. For example:

<section class="">

and

<header class="">

HTML and CSS (Cascading Style Sheets) are explained in Chapter 10. HTML and CSS drive the formatting and style of your overall theme, from a visual standpoint (fonts, colors, images, and so on).

WordPress uses other template files besides the Main Index, such as the Header, Sidebar, and Footer templates. The next section gives you a closer look at a few of them.

The Sidebar template

The filename of the default Sidebar template is sidebar.php. Typically, the sidebar is displayed on the right or left side of your WordPress template. In the default Twenty Fifteen theme, the sidebar is displayed on the right side of the template, by default (refer to Figure 9-3).

The Sidebar template is called into the Header template, which, as mentioned previously, is called into the Main Index template. The Sidebar template gets called in using this template tag (as seen in header.php in the Twenty Fifteen theme):

<?php get_sidebar(): ?>

This code calls the Sidebar template and all the information it contains into your blog page. Chapter 12 addresses some additional ways you can call in the Sidebar template, including having multiple Sidebar templates and using an include statement to pull them into the Main Index template.

In the “Using Tags with Parameters for Sidebars” section later in this chapter, you find information on template tags to use in the sidebar to display the usual sidebar elements, such as a list of the most recent posts or a list of categories.

The Footer template

The filename of the Footer template is footer.php. Usually, the footer sits at the bottom of the page (refer to Figure 9-3) and contains brief information about the site, such as copyright statements, credits to the theme designer or hosting company, or even a list of links to other pages within the site.

The default Twenty Fifteen theme shows a statement that says “Proudly powered by WordPress.” You can use the footer to include all sorts of information about your site, however; you don’t have to restrict it to small bits of information. In this chapter, I cover the typical footer that you see in the default Twenty Fifteen theme.

Similarly to the Header and Sidebar templates, the Footer template is 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 is possible, and common, to wrap two template tags in one PHP function like that, if they appear directly after one another. The examples I have given in this chapter separate them out into single functions to make sure you’re clear on what the actual function is.

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

Other templates

Other templates are in the default Twenty Fifteen theme, and I don’t cover all of them in depth in this chapter, but having at least a basic understanding of them is a good idea. The ones I list in this section give you that good, solid kick in the pants you need to get started with understanding WordPress templates. When you have that task licked, you can move on to learning the rest.

These other (optional) templates include

  • Comments template (comments.php): The Comments template is required if you plan to host comments on your blog; 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’ve published to your blog, 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 in your WordPress site.
  • Search Results (search.php): You can use this template to create a custom display of search results on your site. 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 default 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 have that template included in your theme.

Putting a Theme Together

In this section, you put together a basic theme by using the information on templates and tags I’ve provided so far in this chapter. Template files can’t do a whole lot by themselves. The real power comes when they’re put together.

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 built in to WordPress, allowing you to retrieve the content of another template file and display it along with the content of another template file. Table 9-2 shows the templates and the functions to include them.

Table 9-2 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. For example, if you want 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 that 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 it, 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 provided so far in this chapter. There seem to be endless lines of code when you view the index.php template file in the Twenty Fifteen theme, so I’ve simplified it for you with the following 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.

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

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

    This folder contains the themes that are currently installed in your WordPress blog. (See Chapter 3 for more information on FTP.)

  2. Create a new folder and call it mytheme.

    In most FTP programs, you can right-click and choose New Folder. (If you aren’t sure how to create a folder, refer to your FTP 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 with the filename header.php:

      <!DOCTYPE html>

      <html <?php language_attributes(); ?> class="no-js">

      <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’ );

      if ( function_exists( ‘register_sidebar’ ) ) register_sidebar( array( ‘name’=>‘Sidebar’,

      ));

      ?>

      The Theme Functions file registers the widget area for your site so that you’re able to add widgets to your sidebar using the WordPress widgets available on the Widget page in 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 if ( !function_exists( ‘dynamic_sidebar ‘) || !dynamic_sidebar( ‘Sidebar’ ) ) : ?>

      <?php endif; ?>

      </ul>

      </aside>

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

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

      <footer>

      <p>&copy; 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 (more CSS is covered in Chapter 10 — this example gives you just some very basic styling to create your sample theme):

      /*

      Theme Name: My Theme

      Description: Basic Theme from WordPress For Dummies example

      Author: Lisa Sabin-Wilson

      Author URI: http://lisasabin-wilson.com

      */

      body {

      font-family: verdana, arial, helvetica, sans-serif;

      font-size: 16px;

      color: #555;

      background: #ffffff;

      }

      header.masthead {

      width: 950px;

      margin: 0 auto;

      background: black;

      color: white;

      padding: 5px;

      text-align:center;

      }

      header.masthead h1 a {

      color: white;

      font-size: 28px;

      font-family: Georgia;

      text-decoration: none;

      }

      header.masthead h2 {

      font-size: 16px;

      font-family: Georgia;

      color: #eee;

      }

      header.masthead nav {

      background: #ffffff;

      text-align: left;

      height: 25px;

      padding: 4px;

      }

      header.masthead nav ul {

      list-style:none;

      margin:0;

      }

      #main {

      width: 950px;

      margin: 0 auto;

      padding: 20px ;

      }

      #main section {

      width: 500px;

      float:left;

      }

      #main .hentry {

      margin: 10px 0;

      }

      aside.sidebar {

      width: 290px;

      margin: 0 15px;

      float:right;

      }

      aside.sidebar ul {

      list-style:none;

      }

      footer {

      clear:both;

      width: 960px;

      height: 50px;

      background: black;

      color: white;

      margin: 0 auto;

      }

      footer p {

      text-align:center;

      padding: 15px 0;

      }

      footer a {

      color:white;

      }

Using the tags provided in Table 9-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.

Table 9-3 Template Tags for Blog 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.

get_permalink();

Displays the permalink (URL) of the post.

get_the_author();

Displays the post author’s name.

the_author_posts_url();

Displays the URL of the post author’s site.

the_content(‘Read More…’);

Displays the content of the post. (If you use an excerpt [next item], 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, they are separated by commas.

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.*

*These two tags 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('&laquo; Previous Entries') ?>
<?php previous_posts_link('Next Entries &raquo;') ?>
<?php endif; ?>

warning When typing templates, 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 and then go through the following 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 is HTML5 markup that tells the browser that this is a grouping of content (in this case, blog posts).

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

    This template tag is an if statement that asks, “Does this blog have posts?” If the answer is yes, it 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 is HTML5 markup that tells the browser that this is the start of a new, single article, along with the post_class CSS designation (covered in Chapter 12).

  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 in 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 — 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 clickable (hyperlinked) to the post’s permalink, where the reader can read the rest of the post in its entirety. This tag applies when you’re displaying a post excerpt, as determined by the actual post configuration in 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 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 in the WordPress Dashboard. That’s exactly how many times WordPress will execute The Loop.

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

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

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

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

  15. Type <?php else : ?>.

    This template tag refers to the if question asked in Step 3. If the answer to that question 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 is the message followed by the template tag displayed after the else statement from Step 15. You can reword this statement to have it say whatever you want.

  17. Type <?php endif; ?>.

    This template tag ends the if statement from Step 3.

  18. Type </section>.

    This is HTML5 markup that closes the <section> tag 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 is HTML markup closing 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( ‘&laquo; Previous Entries’ ) ?>

    <?php previous_posts_link( ‘Next Entries &raquo;’ ) ?>

    <?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 it by choosing File image Save As. Type the name of the file in the File Name text box and click Save.

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

tip My Main Index template code has one template tag that I explain in Chapter 12; that template tag is <article <?php post_class() ?> id="post-<?php the_ID(); ?>">. This tag helps you create some interesting styles in your template using CSS, so check out Chapter 12 to find out all about it!

This very simple and basic Main Index template that you just built does not have the standard HTML markup in it, so you will find that the visual display of your blog differs from the default Twenty Fifteen theme. This example was used to give you the bare-bones basics of the Main Index template and The Loop in action. Chapter 10 goes into details 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 out the code provided, I have made this sample theme available for download on my website. The zip file contains the files discussed in this chapter so you can compare your efforts with mine, electronically. You can download the theme zip file here: http://lisasabin-wilson.com/wpfd/my-theme.zip.

Using additional stylesheets

Often a theme uses multiple stylesheets for browser compatibility or consistent organization. If you use multiple stylesheets, the process for including them in the template is the same as with 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 working with a concept called Parent/Child themes, which is the practice of creating a child theme that depends upon a separate parent theme for features and functions. I write more about Parent/Child themes, as well as provide you with additional information on HTML and CSS, in Chapter 11.

Customizing Your Blog Posts with Template Tags

This section covers the template tags that you use to display the body of each blog post you publish. The body of a blog post includes information such as the post date and time, title, author name, category, and content. Table 9-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 9-3 work only if you place them within The Loop (covered earlier in this chapter and found in the index.php template file in the Twenty Fifteen default theme).

Using Tags with Parameters for Sidebars

If you’ve been following along in this chapter as I’ve covered the Header and Main Index templates and tags, you have a functional WordPress site with blog posts and various metadata displayed in each post.

In this section, I give you the template tags for the items commonly placed in the sidebar of a site. I say “commonly placed,” because it’s possible to get creative with these template tags and place them in other locations (the Footer template, for example). To keep this introduction to Sidebar template tags simple, I stick with the most common use, leaving the creative and uncommon uses for you to try when you’re comfortable with building the basics.

This section also introduces tag parameters, which are additional options you can include in the tag to control some of its display properties. Not all template tags have parameters. You place tag parameters inside the parentheses of the tag. Many of the parameters discussed in this section were obtained from the WordPress software documentation in the WordPress Codex at http://codex.wordpress.org.

Table 9-4 helps you understand the three variations of parameters used by WordPress.

Table 9-4 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 parameters

These tags generally 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, they’ll be processed correctly.
  • Boolean: Sets the parameter options to true or false. This parameter can be numeric (0=false and 1=true) or textual. Boolean parameters aren’t placed within quotation marks.

remember The WordPress Codex, located at http://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.

The calendar

The calendar tag displays a calendar that highlights each day of the week on which you’ve posted a blog. Those days are also hyperlinked to the original blog post. Here’s the tag to use to display the calendar:

<?php get_calendar(); ?>

The calendar tag has only one parameter, and it’s Boolean. Set this parameter to true and it displays the day of the week with one letter (Friday = F, for example). Set this parameter to false and it displays the day of the week as a three-letter abbreviation (Friday = Fri., for example). Here are examples of the template tag used to display the calendar on your WordPress blog:

<?php get_calendar( true ); ?>

<?php get_calendar( false ); ?>

List pages

The <?php wp_list_pages(); ?> tag displays a list of the static pages you can create on your WordPress site (such as About Me or Contact pages). Displaying a link to the static pages makes them available so that readers can click the links and read the content you’ve provided.

WordPress has a handy navigation menu–building tool that I cover in Chapter 10. It allows you to build different custom navigation menus. If you like the navigation tool, you may never need to use the wp_list_pages(); template tag. Still, I’m including it here because you may want to use it if you want to have complete control over how the list of pages appears on your website.

The <list> tag parameters use the string style. (Table 9-5 lists the most common parameters used for the wp_list_pages template tag.)

Table 9-5 Most Common Parameters (Query-String) for wp_list_pages();

Parameter

Type

Description and Values

child_of

integer

Displays only the subpages of the page; uses the numeric ID for a page as the value. Defaults to 0 (display all pages).

sort_column

string

Sorts pages with one of the following options:

‘post_title’ — Sorts alphabetically by page title (default).

‘menu_order’ — Sorts by page order (the order in which they appear in the Manage tab and Pages subtab in the Dashboard).

‘post_date’ — Sorts by the date on which pages were created.

‘post_modified’ — Sorts by the time when the page was last modified.

‘post_author’ — Sorts by author, according to the author ID. #. ‘post_name’ — Sorts alphabetically by the post slug.

‘ID’ — Sorts by numeric Page ID.

Exclude

string

Lists the numeric page ID numbers, separated by commas, that you want to exclude from the page list display (for example, ‘exclude=10, 20, 30’). There is no default value.

Depth

integer

Uses a numeric value for how many levels of pages are displayed in the list of pages. Possible options:

0 — Displays all pages, including main and subpages (default).

-1 — Shows subpages but doesn’t indent them in the list display.

1 — Shows only main pages (no subpages).

2, 3 … — Displays pages to the given depth.

show_date

string

Displays the date when the page was created or last modified. Possible options:

' ' — Displays no date (default).

'modified' — Displays the date when the page was last modified.

'created' — Displays the date when the page was created.

date_format

string

Sets the format of the date to be displayed. Defaults to the date format configured in the Options tab and General subtab in the Dashboard.

title_li

string

Types text for the heading of the page list. Defaults to display the text: "Pages". If value is empty ("), no heading is displayed; for example, ‘title_li=My Pages" displays the heading My Pages above the page list.

tip An alternative to using the wp_list_pages() template tag to create a navigation system is to use the built-in feature in WordPress called Menus, which enables you to build custom menus that aren’t completely dependent upon your WordPress pages but that can include links to posts, categories, and custom links that you define. Chapter 10 contains information about the Menus feature, along with the wp_nav_menu() template tag that you use to display menus.

Page lists are displayed in an unordered list (you may know it by the term bulleted list). Whichever term you use, it’s a list with a bullet point in front of every page link.

The following tag and query string displays a list of pages without the text heading "Pages". In other words, it displays no title at the top of the page’s link list:

<?php wp_list_pages( ‘title_li=’ ); ?>

The next tag and query string displays the list of pages sorted by the date when they were created; the date is also displayed along with the page name:

<?php wp_list_pages( ‘sort_column=post_date&show_date=‘created’ ); ?>

technicalstuff Take a look at the way query-string parameters are written:

‘parameter1=value&parameter2=value&parameter3=value’

The entire string is surrounded by single quotation marks, and no white space is within the query string. Each parameter is joined to its value by the = character. When you use multiple parameters/values, you separate them with the & character. You can think of the string like this: parameter1=valueANDparameter2=valueANDparameter3=value. Keep this convention in mind for the remaining template tags and parameters in this chapter.

Post archives

The <?php wp_get_archives(); ?> template tag displays the blog post archives in a number of ways, using the parameters and values shown in Table 9-6. Values that appear in bold are the default values set by WordPress. Here are just a few examples of what you can produce with this template tag:

  • Display the titles of the last 15 posts you’ve made to your site.
  • Display the titles of the posts you’ve made in the past ten days.
  • Display a monthly list of archives.

Table 9-6 Most Common Parameters (Query-String) for wp_get_archives();

Parameter and Type

Possible Values

Example

type (string)

Determines the type of archive to display.

monthlydailyweeklypostbypost

<?php wp_get_archives( ‘type=postbypost’ ); ?>

Displays the titles of the most recent blog posts.

format (string)

Formats the display of the links in the archive list.

html — Surrounds the links with <li> </li> tags.

option — Places archive list in drop-down menu format.

link — Surrounds the links with <link> </link> tags.

custom — Use your own HTML tags, using the before and after parameters.

<?php wp_get_archives( ‘format=html’ ); ?>

Displays the list of archive links where each link is surrounded by the <li> </li> HTML tags.

limit (integer)

Limits the number of archives to display.

If no value, all are displayed.

<?php wp_get_archives( ‘limit=10’ ); ?>

Displays the last ten archives in a list.

before (string)

Places text or formatting before the link in the archive list when using the custom parameter.

No default

<?php wp_get_archives( ‘before=<strong>’ ); ?>

Inserts the <strong> HTML tag before each link in the archive link list.

after (string)

Inserts text or formatting after the link in the archive list when using the custom parameter.

No default

<?php wp_get_archives( ‘after=</strong>’ ); ?>

Inserts the </strong> HTML tag after each link in the archive link list.

show_post_count (Boolean)

This value displays the number of posts in the archive. You would use this if you use the ‘type’ of monthly.

true or 1

false or 0

<? wp_get_archives( ‘show_post_count=1’ ); ?>

Displays the number of posts in each archive after each archive link.

Here are a couple of examples of tags used to display blog-post archives.

This tag displays a linked list of monthly archives (for example, November 2015, December 2015, and so on).

<?php wp_get_archives( ‘type=monthly’ ); ?>

This next tag displays a linked list of the 15 most recent blog posts:

<?php wp_get_archives( ‘type=postbypost&limit=15’ ); ?>

Categories

WordPress lets you create categories and assign posts to a specific category (or multiple categories). Categories provide an organized navigation system that helps you and your readers find posts you’ve made on certain topics.

The <?php wp_list_categories(); ?> template tag lets you display a list of your categories by using the available parameters and values. (Table 9-7 shows some of the most popular parameters.) Each category is linked to the appropriate category page that lists all the posts you’ve assigned to it. The values that appear in bold are the default values set by WordPress.

Table 9-7 Most Common Parameters (Query-String) for wp_list_categories();

Parameter and Type

Possible Values

Example

orderby (string)

Determines how the category list will be ordered.

ID name

<?php wp_list_categories( ‘orderby=name’ ); ?>

Displays the list of categories by name, alphabetically, as they appear in the Dashboard.

style (string)

Determines the format of the category list display.

List
none

<?php wp_list_categories ( ‘style=list’ ); ?> Displays the list of category links where each link is surrounded by the <li> </li> HTML tags. <?php wp_list_categories( ‘style=none’ ); ?>

Displays the list of category links with a simple line break after each link.

show_count (Boolean)

Determines whether to display the post count for each listed category.

true or 1

false or 0

<?php wp_list_categories( ‘show_count=1’ ); ?>

Displays the post count, in parentheses, after each category list. Espresso (10), for example, means that there are ten posts in the Espresso category.

hide_empty (Boolean)

Determines whether empty categories should be displayed in the list (meaning a category with zero posts assigned to it).

true or 1 false or 0

<?php wp_list_categories( ‘hide_empty=0’ ); ?>

Displays only those categories that currently have posts assigned to them.

feed (string)

Determines whether the RSS feed should be displayed for each category in the list.

Rss

Default is no feeds displayed.

<?php wp_list_categories( ‘feed=rss’ ); ?>

Displays category titles with an RSS link next to each one.

feed_image (string)

Provides the path/filename for an image for the feed.

No default

<?php wp_list_categories( ‘feed_image=/wp-content/images/feed.gif’ ); ?>

Displays the feed.gif image for each category title. This image is linked to the RSS feed for that category.

hierarchical (Boolean)

Determines whether the child categories should be displayed after each parent category in the category link list.

true or 1

false or 0

<?php wp_list_categories( ‘hierarchical=0’ ); ?>

Doesn’t display the child categories after each parent category in the category list.

Here are a couple of examples of tags used to display a list of your categories.

This example, with its parameters, displays a list of categories sorted by name without showing the number of posts made in each category; the example also displays the RSS feed for each category title:

<?php wp_list_categories( ‘orderby=name&show_count=0&feed=RSS’ ); ?>

This example, with its parameters, displays a list of categories sorted by name with the post count showing and shows the subcategories of every parent category:

<?php wp_list_categories( ‘orderby=name&show_count=1&hierarchical=1’ ); ‘>

Getting widgetized

About 99.99 percent of the WordPress themes available today are coded with widgetized sidebars — which means you can use the widgets within WordPress to populate your sidebar area with content, navigation menus, and lists.

With widgets in place, you generally have no reason to mess around with the code in the sidebar.php template file because most of the content you want to add into your sidebar can be added through the use of widgets.

In a WordPress theme, the Theme Functions template (functions.php) and the Sidebar template (sidebar.php) create the functionality and the possibility for widgets to exist within your theme. You’re not limited to where you place and use widgets, by and large. I am using the Sidebar template (sidebar.php) in this example.

First, you have to define the widgets in your theme. This means that you need to alert WordPress to the fact that this theme can handle widgets — which is known as registering a widget with the WordPress software. To register a widget, add the register_sidebar function to the Theme Functions template (functions.php). In the functions.php file in the Twenty Fifteen theme, the code for registering a widget looks like this:

register_sidebar( array(

‘name’ => __( ‘Widget Area’, ‘twentyfifteen' ),

‘id’ => ‘sidebar-1’,

‘description’ => __( ‘Main sidebar that appears on the left.’, ‘twentyfifteen’),

‘before_widget’ => ‘<aside id="%1$s" class="widget %2$s">’,

‘after_widget’ => ‘</aside>’,

‘before_title’ => ‘<h1 class="widget-title">’,

‘after_title’ => ‘</h1>’,

) );

Within that code, you see seven different arrays. An array is a set of values that tells WordPress how you would like your widgets handled and displayed:

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

With that code in your functions.php file, WordPress now recognizes that you’ve registered a widget called Widget Area for your theme and makes the widget area available for you to drag and drop widgets onto the Widgets page in the Dashboard. All that’s left to do now is to call that widget into your sidebar.php file. By doing so, you allow the widgets to display on your site. Follow these steps to call widgets to your site (these steps assume that the widget code isn’t already in the Sidebar template):

  1. Click the Editor link below the Appearance menu.

    The Edit Themes page opens.

  2. Click the Sidebar (sidebar.php ) template.

    The Sidebar template opens in the text box on the left side of the page.

  3. Type the following code in the Sidebar (sidebar.php ) template:

    <?php if ( ! dynamic_sidebar( ‘Primary Widget Area’ ) ) : ?>

    <?php endif; ?>

    The parameter within the dynamic_sidebar template tag corresponds to the name that you provided in the widget array called name earlier in this section. It must be the same; otherwise, it will not display on your website.

  4. Click the Update File button.

    The changes you’ve made to the Sidebar (sidebar.php) template file are now saved.

tip You can register an unlimited number of widgets for your theme. This flexibility allows you to create several different widgetized areas and widget features in different areas of your site. Chapter 12 goes into more detail about using different Sidebar templates to create different widgetized areas and features on your site.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.5.68