Quantcast
Channel: Back-End Development - WPShout
Viewing all articles
Browse latest Browse all 159

WordPress Theme Development: Adding Functionality with functions.php

$
0
0

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. It’s often usefully simplified into being called “a WordPress theme’s plugin.”

If you’re interested in under more of the key concepts, check out our free course on getting started with learning to develops WordPress themes. This content (and that entire free course) is made up of sample chapters from our “learn WordPress development” guide Up and Running, now in its revised and expanded 3rd Edition for 2018.

If you like this chapter, be sure to give that a look. There are nearly 40 chapters in Up and Running, each as useful as this article. It’s the best guide to WordPress development out there.

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 for 2018, 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 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 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.

Viewing all articles
Browse latest Browse all 159

Trending Articles