Course: WordPress Theme Development (Core Concepts)

up and running: wordpress theme development

This is an introduction to the core concepts of WordPress theme development and comes from the upcoming Second Edition of our “learn WordPress development” course Up and Running.

This post covers the three most important concepts of WordPress theme development:

  1. The Template Hierarchy
  2. Processing Posts with The Loop
  3. Adding Functionality with functions.php

We’ll take you through each one and – like in Up and Running, at the end there’s a Summary Limerick and Quiz to reinforce what you’ve learned.

You can also unlock three bonus video tutorials by signing up to our email list. These accompany each of the three topics covered in this post:

Enjoy the post below, and if you want to learn more about WordPress development – look out for Up and Running launching in its Second Edition on March 21.

Core Concept 1 of WordPress Theme Development: The Template Hierarchy

Key Takeaways:

  • The WordPress template hierarchy determines which PHP template files will be used to construct a given webpage on your site, based on the type of post content requested: for example, whether the webpage displays a Page, a Post, or an archive of many Posts.
  • The template hierarchy follows a defined order set in WordPress itself. Learning this hierarchy will let you pinpoint which of your webpages will use which template.

As we work through this chapter, remember the following analogy: WordPress is a factory that processes raw material, posts, into finished products, webpages.

In this chapter, we’re in the stage of the production process where a bundle of posts has been fetched out of the warehouse (the database), and are all ready to be assembled and made to display beautifully by our assembly line, the WordPress theme.

However, the theme provides a lot of possible lines to send those posts down: our different PHP templates. Putting our posts through index.php will result in a webpage that looks one way; putting it through home.php, archive.php, or page.php will give very different results.

How do we know which assembly line a given bundle will go down? With the WordPress template hierarchy. The template hierarchy is a built-in system in WordPress that specifies which line to send a given bundle of posts down, based on properties of the bundle itself.

This chapter explains how the template hierarchy makes its decisions.

index.php: The Ultimate Fallback

For the factory to work, there must always be at least one assembly line that can take any given bundle of posts. This is why every WordPress theme must have an index.php template file.

index.php is the final fallback. Whether you’re building a webpage around all the Posts you wrote in September 2016, or around a single Page, or around the results of a search for all the posts (of any post type) containing the phrase “snow tires,” or around one or more posts of a totally custom post type, such as Recipe or Movie Review, the rule is the same: If the template hierarchy doesn’t find something else to use, it falls back to index.php.

So WordPress can always build out a webpage using index.php if it doesn’t have a more fitting template file to use. However, it will try to find a better template file if one exists.

The Rest of the Hierarchy

WordPress has created some really powerful choice trees for deciding which template to display. From the Codex:

A visual guide to WordPress theme development

Click to enlarge

We won’t be including this in Resources, because it was created by the lovely Michelle Schulp, not us. You can view the full file on this page: https://codex.wordpress.org/Template_Hierarchy#Visual_Overview.

To see what’s going on, let’s follow an example page from left to right on the diagram.

Tracing a Site’s “About Us” Page Through the Template Hierarchy

Let’s see what happens for an imaginary site’s “About Us” page, written as a Page (that is, a post of type Page) and located at site.com/about.

Bundle Type: “Singular Page”

Starting from the very left of the diagram: what’s our “page type”? This question really means, “What kind of bundle of posts are we dealing with?” The answer is “Singular Page,” because the warehouse has sent us a bundle containing only one single (“singular”) post, rather than lots of posts together.

Static Page

Next up, we have two options: is this a “Single Post Page” or a “Static Page”? Don’t let the language confuse you: what they’re really asking is, “Is this a single post of type Post or of any custom post type, or is it a single post of type Page?” It’s the second one, which they’re calling a “Static Page.”

Page Template: Default Template

Okay, are we using a “Custom Template” or a “Default Template”? We’ll get into custom templates later, in Understanding and Creating WordPress Custom Post Templates. You can read this as, “Did you select something other than ‘Default Template’ in the Page Editor?”

Custom post templates

In this case, let’s say we’re not using a custom template on our “About” page. So the right answer for us is “Default Template.”

Template Used: page.php, with index.php Fallback

The next two nodes—page-$slug.php and page-$id.php—are little-used options that let you create templates for individual pages. We don’t have those, so we’ll skate right through them.

That leaves us with the template that will actually display our About page: page.php. And if our theme doesn’t have page.php, we’ll slide all the way back to our ultimate fallback: index.php.

We’ve just finished our first trip through the WordPress template hierarchy. Based on the number and type of posts we’ve retrieved from the database, we’re able to know exactly which of our PHP templates WordPress will rely on to build out the corresponding webpage.

A Second Example: The Blog Index

Let’s take a second trip through the template hierarchy, this time with the site’s blog index page. This is the page on your website that displays your most recent Posts. But which page is this, specifically? It depends on your site’s settings in Settings > Reading:

If you leave the setting as its default, then your blog index is your site’s homepage: the webpage you see when you navigate to yourdomain.com.

However, you can also set your blog index to appear at the URL of an existing “static page” (meaning a Page). Choosing a “static page” for your blog index page will change the blog index’s URL to something like yourdomain.com/blog, for a Page titled “Blog,” or yourdomain.com/news, for a Page titled “News.”

Whatever webpage your blog index is, WordPress knows when you’re visiting it, and it’ll fetch a bundle of your most recent Posts.

Bundle Type: “Blog Posts Index Page”

When this bundle hits the template hierarchy—starting from the left of the diagram—the hierarchy recognizes your “Page Type” as “Blog Posts Index Page.”

Template Used: home.php, with index.php Fallback

As you can see, this tree is simple: your blog index page will display the contents of home.php. If that doesn’t exist, it’ll default back to good old index.php.

Seeing the Whole Hierarchy

Are you starting to get how the template hierarchy works? Once you understand the basic concept, making WordPress themes that benefit from this knowledge simply requires creating and modifying the proper template files for the types of webpages you wish to affect.

The diagram above is great, but there are a few other great ways to visualize and understand the template hierarchy:

  • Template Hierarchy on the WordPress Codex, at: http://codex.wordpress.org/Template_Hierarchy. The Codex is the canonical source for information on the template hierarchy, and on WordPress itself. Learn to love it! On this page, you can learn what each type of template file does.
  • Interactive Template Hierarchy Resource, at: http://wphierarchy.com/. This is an interactive version of the Codex’s template hierarchy image. Click on any node to get help understanding what it means and when it applies.
  • WPTuts+ Cheat Sheet, at: http://wp.tutsplus.com/articles/wordpress-cheat-sheets-template-heirarchy-map/. Especially if you understand WordPress conditional functions like is_home(), we really appreciate the brevity of this visual map. It’s not exhaustive, but it’s easy to read.

Now You Understand the Template Hierarchy

The WordPress template hierarchy is a major part of the magic of WordPress themes and WordPress theme development. Now that you understand its basic workings, you can really dive in and understand exactly which templates apply in which cases.

Get Rid of the Guesswork with Which Template

One final recommendation: If you ever get stuck knowing which template is operating on a particular webpage, you can install a plugin: Which Template. It’s located at https://wordpress.org/plugins/which-template/. When you browse the site while logged-in, it prints the current template into your admin bar, as follows:

The The template currently in use – very useful for WordPress theme development

Which Template indicates that this webpage is using the active theme’s MARKDOWN_HASH6ce624532346493b7a0d1a63ecfc68ceMARKDOWN_HASH (top right of picture).

This plugin can be a great way to learn the template hierarchy in depth, as you see exactly which template is active at each part of your site.

Next up, something truly awesome in WordPress theme development: The Loop!

Summary Limerick

Do you want to know how WordPress chooses
Which PHP template it uses?
Then let’s learn the parts
of the hierarchy charts,
And the choices it makes won’t confuse us!

Quiz Time!

  1. The WordPress template hierarchy:
    1. Is a customizable set of rules a developer writes for his or her PHP templates
    2. Allows developers to create new kinds of PHP templates
    3. Dictates which PHP template will be used to construct a given webpage
  2. In processing a category archive page—which displays multiple posts that belong to one category—WordPress will first attempt to use which of the following:
    1. archive.php
    2. category.php
    3. index.php
  3. If a particular template file in the hierarchy doesn’t exist, WordPress will:
    1. Move to the next file in the relevant decision tree, ultimately falling back to index.php for all trees
    2. Create and use a standardized version of the missing template file
    3. Display an error indicating that the desired template file could not be found

Answers and Explanations

  1. C. The template hierarchy is how WordPress decides which of the active theme’s PHP template files it will use to construct a specific page.
  2. B. Of the options, it will first try category.php, then archive.php, then index.php.
  3. A. index.php is the template hierarchy’s ultimate fallback, for all types of pages.

Core Concept 2 of WordPress Theme Development: Processing Posts with The Loop

Key Takeaways:

  • The Loop is an extremely important topic in WordPress theme development: it is how WordPress renders a bundle of posts fetched from the database into an HTML webpage.
  • The Loop is a PHP while-loop that runs once per fetched post. Inside it, theme developers set repeated rules for how each post should display, primarily using WordPress’s template tags.
  • The Loop should exist in every theme file that is part of the WordPress template hierarchy. Customizing The Loop is a major way in which themes create different views and layouts for webpages that display different kinds of posts (for example, Posts and Pages).

The Loop is perhaps the key concept of WordPress theme development, so you’ll definitely want to wrap your head around it. Fortunately, it’s not that complicated! Our goal here is to make the concept clear first, and then to move on and show you how the code works.

The Loop in Plain English

In this section, no programming. We’ll just go over basic concepts.

The Loop Exists in WordPress PHP Template Files

As we covered in the last chapter, a theme is made up, first and foremost, of its PHP template files. The WordPress template hierarchy dictates which webpages (and post bundles) to associate with which template files: for example, page.php for a request that pulls a site’s “About” page, home.php for a request that pulls the site’s blog index page, and index.php as a universal fallback if something higher up in the hierarchy isn’t triggered.

Once we know which template file we’re working with, it’s time to get into the guts of the file itself, and that’s where we’ll find The Loop.

The Loop is What Processes Posts

You specify formatting inside The Loop, and WordPress applies that formatting to every post in the fetched bundle—which is why it’s called The Loop.

The WordPress Loop is how WordPress processes any bundle of fetched posts.

Inside The Loop, you specify how you want each post in the fetched bundle to be laid out. WordPress will “loop through” the bundle, and reuse the specified format for every post in the bundle—which is why it’s called The Loop.

So The Loop is most obvious on, for example, your blog index page, where WordPress cycles through lots of blog posts, reusing the format we’ve specified for each one.

However, if there’s only one post on the webpage—when someone requests, say, a single blog post, or the site’s “About” page—WordPress will still use the core concept of The Loop to display the (single) post on the webpage.

The Loop is the Customizable Heart of Template Files

Changing Loop contents is a primary way to make your template files behave differently.

The Loop is the engine of any template file, and it’s highly customizable; it varies file-by-file. Changing Loop contents is a primary way to make your template files behave differently.

For example, you might want to make your blog index page (controlled by your theme’s home.php) show only one-paragraph excerpts of your blog posts, instead of the whole content. To do this, you’ll use the the_excerpt() template tag inside home.php‘s Loop. (We cover template tags later, in The Magic of the_() and get_the_() Post Template Tags—they’re cool!)

At the same time, you still want the webpages for your individual blog posts (controlled by single.php) to display the entire article contents, not just an excerpt. So inside the single.php Loop, you’ll use the the_content() template tag, instead of the_excerpt().

Being able to dictate these differences is a lot of what WordPress theme development is all about.

An Example Loop

Some template files are very little but The Loop.

Below you’ll see the single.php file for WordPress’s popular Twenty Fifteen theme. The Loop is on lines 15 to 43. We won’t scare you yet with what’s inside The Loop itself (so lines 18 to 39 are hidden)—but notice that single.php isn’t much but The Loop! In other words, The Loop is doing almost all the work that makes this template file display its contents.

The Loop inside the Twenty Fifteen theme’s MARKDOWN_HASH6ce624532346493b7a0d1a63ecfc68ceMARKDOWN_HASH.

So that’s a Loop in the wild. Now let’s leave Twenty Fifteen alone and talk about the general anatomy of a Loop in any theme.

The Minimal Loop

Here we’ll look at the bare-bones PHP code that makes up The Loop. This code can be written two ways, and both do exactly the same thing. Either:

<?php
/* Environment: We're inside a theme template file in the WordPress template hierarchy */

if ( have_posts() ) {
    while ( have_posts() ) {
        the_post(); 

        // (Loop contents will go here)

    } // end while
} // end if

Or…

<?php
/* Environment: We're inside a theme template file in the WordPress template hierarchy */

if ( have_posts() ) :
    while ( have_posts() ) :
        the_post(); 

        // (Loop contents will go here)

    endwhile;
endif;

Don’t get too hung up on there being two ways to write The Loop—they’re just two ways of “punctuating” PHP, and they mean the same thing. We prefer the second way of writing it, so we’ll be sticking with that one through the rest of the chapter.

How The Loop Works

The Loop really is a loop, in the programming sense.

In this section, we’ll offer a line-by-line explanation of the second Loop example above (the one with the endwhile in it).

The first thing to notice is that The Loop really is a loop, in the programming sense. In other words, it iterates (loops) over a set of WordPress posts—and doesn’t stop until it runs out of posts. Here’s how that works, line-by-line:

if ( have_posts() ) :

The Loop first asks of the broader WordPress environment, “Have any posts been fetched for me to process?” It asks this using a WordPress function called have_posts(). That function returns (gives back) either true, if there are posts to process, or false, if there aren’t.

If the answer we get back from have_posts() is true, then what’s inside the if-statement—which is The Loop itself—will operate. If not, then our PHP engine skips right over The Loop, because there’s nothing to loop through!

while ( have_posts() ) :

Since we’ve passed inside the initial if-statement, we know that we do indeed have posts to loop through. So this line is where The Loop’s actual loop starts. It’s a PHP while loop: something that keeps iterating as long as (“while”) a condition is true.

In English, this line says “While we still have posts to process:” In other words, this loop will execute the code inside it once per post, while there are still posts to act on. When there are no more posts, The Loop will stop, and the page will move on to the next thing in this PHP template.

the_post();

Remember, we’re now inside the while loop described above. This line says, “Since we’ve got a post to work on, let’s begin by queueing up the current post.”

the_post() is what does the “queueing up”—it basically sets up the next fetched post object to be worked on by the WordPress processes available to us within The Loop. The Loop requires this function, but we don’t have to know too much more about it than this.

// (Post content will go here)

This section is the main contents of The Loop. It’s where we’ll get to be creative—where we’ll actually write code to work with each fetched post, one by one. Since it’s the section that we’ll write ourselves, it’s currently empty except for a placeholder PHP comment. We’ll explore this section further in the rest of this chapter.

endwhile;

This is PHP’s way of saying: “We’re done with the while loop we were in.” Anything between while () : and endwhile; is inside that loop; anything after is outside it, and will only be run once the while loop itself is finished.

endif;

This is PHP’s way of saying: “We’re done with the if-statement we were in.” Anything between if () : and endif; only executes if the if-statement is true; anything after it isn’t affected by the if-statement itself.

An Example of The Loop in Action

Now that we understand the basic “skeleton” syntax of The Loop, here’s a very simple Loop that actually does something:

<?php 
/* Environment: We're inside a theme template file in the WordPress template hierarchy */

if ( have_posts() ) :
    while ( have_posts() ) :
        the_post(); ?>

        <article class="full-article">
            <h2><?php the_title(); ?></h2>
            <?php the_excerpt(); ?>
        </article>

    <?php endwhile;
endif;

What This Loop Outputs

For each post in the bundle, this Loop first creates an HTML <article> tag. Inside that, it displays first the title, and then a short excerpt—by default, the first 55 words followed by […]—of the current post.

So taking some Posts from the blog of our site Press Up as examples, the Loop above outputs:

<article class="full-article">
    <h2>What Your Minimum Viable Product Should Be Measuring</h2>
    <p>In our last article we introduced you to the idea of the Minimum Viable Product (MVP), and covered some of the internal challenges that often arise when you prepare to share a beta version of your idea. An MVP isn't just a quick, cheap version of your product that you're releasing because it's easy. On […]</p>
</article>


<article class="full-article">
    <h2>Starting Small: Creating a Minimum Viable Product</h2>
    <p>A common mistake entrepreneurs make is to start with a very specific idea and grind as hard as possible to make it work. This might work out great—but as many entrepreneurs learn, it's far too easy to rush through, or entirely overlook, the process of refining our initial ideas into something people truly want. Not […]</p>
</article>


<article class="full-article">
    <h2>How to Plan a Successful Web Project</h2>
    <p>It's too easy to plan out a web project in terms of technologies rather than solutions. Too many web projects don't meet their goals. The project could be the wrong solution for the right goal, the right solution for the wrong goal—or, perhaps worst of all, a shiny solution for no goal. The problem is […]</p>
</article>

// (And so on for many more articles)

Patterns to Notice

A couple of things to notice in this Loop example:

  1. Notice how we move in between plain HTML and PHP. Remember, anything not inside <?php ?> is pure HTML: in our case, that’s the <h2> and <article> tags. Those get printed out directly to the webpage every time The Loop iterates over a new post.
  2. The real meat here—and where we’re getting deep into the magic of WordPress—is the two PHP template tags we’re using: the_title(), which, when used inside The Loop, prints out the current post’s title; and the_excerpt(), which prints out the beginning of the post’s content. We cover template tags in detail in The Magic of the_() and get_the_() Post Template Tags.

If you made a theme whose only template hierarchy file was index.php, and pasted the above Loop into that index.php file, it would work. Your site’s homepage would display all the titles and excerpts of your most recent Posts, your site’s “About” page would display the title and excerpt of that Page’s copy, and so on.

You’re Now Loop-Literate for even better WordPress theme development

We hope that this explanation of The Loop makes its core principles clear. Most real themes’ Loops will be more complicated—but this is a real start.

Again, you’ll learn more about programming the innards of The Loop with template tags like the_content() in The Magic of the_() and get_the_() Post Template Tags. For now, though, you’re Loop-literate, and that’s a great thing! This is one of the most important parts of WordPress theme development.

Summary Limerick

The Loop is a loop that runs while
There are still unworked posts in the pile.
Each post, and its sequels,
Are marked-up as equals
To form the HTML file.

Quiz Time!

  1. The Loop is present in:
    1. Files in the template hierarchy like single.php and page.php
    2. functions.php
    3. “Always-used” WordPress templates like header.php and footer.php
  2. The Loop typically does not contain:
    1. A PHP for loop
    2. A PHP while loop
    3. A PHP if-statement
  3. The Loop runs:
    1. Once
    2. Once per fetched post
    3. Once per post in the database

Answers and Explanations

  1. A. The files in the WordPress template hierarchy should always include The Loop; other theme files generally don’t.
  2. A. No for( ) {} logic is used in a regular version of The Loop.
  3. B. The Loop whiles through each post that has been fetched to build the current page—not once for each post in the whole database. That’d be crazy: a WordPress site can have hundreds or even thousands of posts in its database, and building a page often requires fetching only one of those posts, or a handful.

Core Concept 3 of WordPress theme development: Adding Functionality with functions.php

Key Takeaways:

  • functions.php is a specially named PHP file that can be located inside any WordPress theme. WordPress knows to execute the code in functions.php during its normal PHP processing.
  • functions.php‘s job is to add custom functionality to the theme and site. It is composed of PHP functions—small bits of PHP code that add or change functionality across the site.
  • As functions.php is inside the theme, its functionality additions should all be presentational in nature. Examples include: enqueueing CSS stylesheets and presentational JavaScript files, enabling featured images, registering custom image sizes, and registering navigation menus and widget areas.

functions.php is the “brain” of a WordPress theme: it’s where we dictate all kinds of presentational functionality—PHP functions that control how things display, rather than the site’s underlying data—for the theme.

In this chapter, we’ll cover how to work with functions.php, and some of what it can do for your theme and site.

What functions.php Is

functions.php exists to provide useful presentational PHP functions: small bits of work that change how the site displays.

A theme’s functions.php exists to provide the theme with useful presentational PHP functions: small bits of work that change how the site displays in defined ways.

Keeping it Presentational

Ask yourself: “If I changed themes, would I lose lots of data, or would things just display differently?” It should be the latter.

Presentational changes don’t alter the site’s underlying data: things like post content, registered users, custom post types, taxonomies such as tags and categories, or sitewide data like “site title” or “customer discount codes.”

To know whether a function qualifies, ask yourself: “If I changed themes, would I lose data, or would things just display differently?” If you’d lose data (a post type would disappear, you’d lose your customer discount codes, etc.), then you’ve strayed from the presentational role of themes.

functions.php Autoloads, Before the Rest of the Theme

Because functions.php autoloads first, its functions are available anywhere in your theme.

functions.php is a PHP file which WordPress knows to examine as part of its “factory” process. It’ll ignore most file names (like functionz.php) by default, but it knows to open up an active theme’s functions.php, see what’s inside, and execute it.

WordPress understands that your theme’s other files may rely on functions in functions.php. That means the PHP engine needs to load functions.php before it loads the pages in the template hierarchy.

The autoloading of functions.php means that its functions are available to you in any of your theme’s PHP files. As a result, it’s the place in your theme to put WordPress function calls that should always run, or be available. This is an incredibly valuable part of WordPress theme development.

Uses of functions.php

Let’s take a look at just a snippet of WPShout’s functions.php, and see what it’s doing for us:

<?php

// Add theme support for featured images, and add a few custom image sizes
add_theme_support( 'post-thumbnails' ); 
add_image_size( 'featured-image-large', 640, 294, true );
add_image_size( 'featured-image-small', 200, 129, true );
add_image_size( 'featured-image-tiny', 124, 80, true );

// Enqueue theme JavaScripts and CSS styles
function wpshout_scripts( ) {
    // Enqueue JS that gives the search box a default value
    wp_enqueue_script( 
        'search-box-value',
        get_stylesheet_directory_uri() . '/js/search-box-value.js',
        array( 'jquery' )
    );

    // Enqueue JS that sets a dynamic page minimum height
    wp_enqueue_script( 
        'page-min-height',
        get_stylesheet_directory_uri() . '/js/page-min-height.js',
        array( 'jquery' )
    );

    // Enqueue main theme stylesheet
    wp_enqueue_style( 
        'wpshout-style',
        get_stylesheet_uri()
    );
}
add_action( 'wp_enqueue_scripts', 'wpshout_scripts' );

// Register main navigation menu
function wpshout_register_menu( ) {
    register_nav_menu( 'main-nav', 'Main Nav' );
}
add_action( 'init', 'wpshout_register_menu' );

The remainder of the chapter will look at each piece of the code above.

Creating Globally Available Functions

functions.php is where to add functions that alter how WordPress runs on all page loads.

functions.php is where you’ll add functions that alter how WordPress runs on every page load. We’re doing a couple of those in the snippet above:

Adding Featured Image Support and Custom Image Sizes

// Add support for featured images and image sizes
add_theme_support( 'post-thumbnails' ); 
add_image_size( 'featured-image-large', 640, 294, true );
add_image_size( 'featured-image-small', 200, 129, true );
add_image_size( 'featured-image-tiny', 124, 80, true );

This first block uses a WordPress function called add_theme_support() to tell WordPress that the theme will be using featured images. (An old term for featured images is “post thumbnails,” which is why the function takes 'post-thumbnails' as an argument.)

Next, the block uses another WordPress function called add_image_size() to register three special image sizes we define: featured-image-large, featured-image-small, and featured-image-tiny. Every time we upload a new image to the site, WordPress will now generate resized versions of that image with the dimensions we’ve specified: 640px wide by 294px tall, and so on.

Registering a New Navigation Menu Area

// Register main navigation menu
function wpshout_register_menu( ) {
    register_nav_menu( 'main-nav', 'Main Nav' );
}
add_action( 'init', 'wpshout_register_menu' );

This block uses a WordPress function, register_nav_menu(), to register a new navigation menu. This function call is wrapped in another function which we’ve written: wpshout_register_menu(). To do the registering, we use the WordPress function add_action() to hook wpshout_register_menu() onto a WordPress action hook called init.

Don’t worry too much about that terminology right now: we’ll explain it in WordPress Hooks, Actions, and Filters: What They Do and How They Work. What it means is that wpshout_register_menu() will now run every time WordPress runs its init process—which WordPress does near the beginning of every webpage load.

So we’re able to make wpshout_register_menu() run toward the beginning of every webpage load. And what does wpshout_register_menu() do? It uses register_nav_menu() to register—cause WordPress to know about—a new navigation menu area titled “Main Nav.”

Loading Globally Needed Resources

functions.php is where you register globally needed JavaScript files and CSS stylesheets.

functions.php is also where you load in resources that you’ll need across the site. This means, most prominently, custom CSS stylesheets and (presentational) JavaScript files—which you load by enqueue-ing them.

// Scripts and styles
add_action( 'wp_enqueue_scripts', 'wpshout_scripts' );
function wpshout_scripts( ) {
    // JS that gives the search box a default value
    wp_enqueue_script( 
        'search-box-value',
        get_stylesheet_directory_uri() . '/js/search-box-value.js',
        array( 'jquery' )
    );

    // JS that sets a dynamic page minimum height
    wp_enqueue_script( 
        'page-min-height',
        get_stylesheet_directory_uri() . '/js/page-min-height.js',
        array( 'jquery' )
    );

    // Load main stylesheet
    wp_enqueue_style( 
        'wpshout-style',
        get_stylesheet_uri()
    );
}

Again, this block looks complicated if you don’t understand WordPress hooks and the wp_enqueue_() functions, but it boils down to the following statement: “On every page, we want to load the files search-box-value.js, page-min-height.js, and the theme’s own style.css,” plus instructions for how to find those files. You’ll learn a lot about wp_enqueue_() in Including Custom Scripts and Styles In WordPress.

With this code in place, when you load a webpage on the site, all three of those files load right along with it, and their functionality will change how the webpage looks and acts.

Now You Get the Fundamentals of functions.php

We’ve covered the core principles of how functions.php works within WordPress theme. development. If you just got hit with a lot of PHP functions you didn’t understand, don’t worry: that’s exactly where we’re headed! The key point is that functions.php adds presentational functionality of all kinds to your theme, and you now understand how.

Summary Limerick

The brains of a theme, you should see,
Is one file: functions.php.
It adds crucial functions
At just the right junctions,
And it tells scripts and styles where to be.

Quiz Time!

  1. functions.php:
    1. Is an arbitrary (but common) name for the theme’s main functions file
    2. Is responsible for adding presentational functionality to the theme
    3. Dictates which PHP template will be used to construct a given webpage
  2. You could just as easily write functions.php‘s functions inside individual template files, except:
    1. WordPress cannot interpret those functions unless they occur inside functions.php
    2. This would negatively affect the site’s page load times
    3. Many functions make the most sense applied across the site, regardless of the page template used
  3. The following would not be a good function to add to functions.php:
    1. A function that alters the permissions of the Editor user role
    2. A function that adds a new CSS stylesheet
    3. A function that dictates what image sizes to create when a new image is uploaded

Answers and Explanations

  1. B. functions.php is the common WordPress way to add functionality to themes.
  2. C. You can declare new PHP functions in any PHP file, but it’s best to put broadly applicable functions in functions.php, because that guarantees their availability wherever in the theme you need them.
  3. A. Because changes to user permissions affect how a site’s data is structured rather than how it displays, those changes shouldn’t live in themes. They should generally go into plugins instead.

 

And don’t forget – if you want to continue to learn WordPress development (and more WordPress theme development) then check out Up and Running. It’s where this great content came from, limericks and all :)


2 Responses

Comments

  • Ben says:

    This tutorial is amazing. I’ve never developed a wordpress theme before and after going through this guide I managed to develop a theme for comparecarinsurance.co.za. Thanks for providing such an indepth guide. Everything else I found online didn’t come close to the detail you’ve provided. Keep up the great work.

Pingbacks