Adding Functionality with functions.php, a Heart of WordPress Theme Development

This article introduces one of the most important topics in WordPress development: functions.php. The functions file is one of the complex, interesting, and powerful in the arsenal of a WordPress theme. What follows

This functions.php tutorial, and our free course on learning to develop WordPress themes, are all chapters from our “learn WordPress development” guide Up and Running, now in its revised and expanded 3rd Edition.

If this material’s helpful to you, check out Up and Running. It’s made of nearly 40 chapters, each as useful and carefully written as this article, and it truly is the best way to learn WordPress development.

The Best Way to Learn WordPress Development

Get Up and Running Today!

Up and Running is our complete “learn WordPress development” course. Now in its updated and expanded 3rd Edition, it’s helped hundreds of happy buyers learn WordPress development the fast, smart, and thorough way.

Here’s what one reader has to say:

“Other courses I’ve tried nearly always lack clear explanations for why WordPress does things a certain way, or how things work together. Up and Running does all of this, and everything is explained clearly and in easy-to-understand language.” -Caroline, WordPress freelancer


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 functions.php tutorial, 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.

In a WordPress theme, 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 for functions inside functions.php.

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.

In WordPress, 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 Custom Scripts and Styles In WordPress. We also have free Quick Guides that go into more detail on this topic:

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.

 


Thanks for reading our WordPress functions.php tutorial. This was one chapter from our full WordPress development resource, Up and Running. If you want to learn WordPress development the fast, smart, and thorough way, give Up and Running a look:

The Best Way to Learn WordPress Development

Get Up and Running Today!

Up and Running is our complete “learn WordPress development” course. Now in its updated and expanded Third Edition, it’s helped hundreds of happy buyers learn WordPress development the fast, smart, and thorough way.

Here’s what our readers have to say:

“As a new WordPress developer, I struggled with how to fully implement PHP and use hooks and filters with the themes I was customizing. Once I got my hands on Up and Running, it all seemed to “click” much easier. This is my go-to reference for WordPress development and I highly recommend it everyone from novices to mid-level developers.” -JeriBeth, WordPress developer

“You guys rock! I have taken several WordPress theme development courses and read two books on it. By a landslide, yours is better because you have been careful to not talk over people’s heads.” -John, WordPress freelancer


4 Responses

Comments

  • Rukhsar says:

    Great article on functions.php. I have written an article on wordpress functions.php similar to this one.

    Your site always provides useful content to WordPress developers. Looking forward more ones from you.

    Thanks for sharing.

  • Thanks for this guide. But what’s the difference between using snippet plugin and using direct function.php coding to activate a feature in wp?

  • Yves says:

    Great guide. Thanks!
    I have the feeling that you are the one who could tell me what is the use of the “10,4” part, in this:
    add_filter(‘get_bsearch_excerpt’, ‘get_custom_bsearch_excerpt’, 10, 4);

    ?

    Would be greatly appreciated.
    I have been searching for the answer for a long time.

    Thanks!

    • Fred Meyer Fred Meyer says:

      Hi Yves, Sure!

      The third argument, 10, is priority: what order this filter function will execute relative to all the other filter functions hooked to the same filter.

      So if there was another function that looked like this:

      add_filter('get_bsearch_excerpt', 'another_custom_function', 9, 4);

      Then it would execute before the function you typed out above. And another function:

      add_filter(‘get_bsearch_excerpt’, ‘yet_another_custom_function’, 11, 4);

      Would execute after both of those functions. In general, functions with larger numbers are more “important,” because they’re the last ones to act on or filter WordPress’s output, after all other similar functions have already run.

      The fourth argument, 4, refers to how many arguments the filter function is passing along. Whoever wrote the apply_filters() call for get_bsearch_excerpt() indicated that that filter could pass along at least 4 arguments for any filter function to work with. The 4 in the text you pasted in indicates that you’ll take the first 4 of those arguments to actually work with. If you wrote 1 instead, it means you’re only bringing in the first argument of the ones that the filter makes available.

      Hope that helps!

Add a Comment

Your email address will not be published. Required fields are marked *