Functions Template File Development

Functions.php is finally here on Let’s Build A WordPress Theme from scratch! Your functions template file in WordPress is really the engine behind your theme. It controls a lot of specific functions that you website will require to run, and for you to be able to better take control of it. The functions file is really limitless. You can go out and look for WordPress code snippets and 90{d28a336400473281ecafcd3e581d1c42e2ddc167997abc26aab972fb90aa55e1} of those snippets will tell you to put them in the functions.php file. Because of this fact, I will only be covering generic functions that you can use to run your WordPress website.

This is the ninth article in the Let’s Build A WordPress Theme From Scratch Series.

Functions.php

In the code below I will show you how to:

  • Register a menu
  • Add various theme supports
  • Register widget areas / sidebars
  • Briefly touch on Enqueuing Files
  • Show you an advanced example of code that will display related posts on your individual post pages

Go ahead and scan over the code and see if you can’t decipher things before I explain them in detail.

<?php
/***********************************************************************************************/
/* Add Menus */
/***********************************************************************************************/
function register_my_menus(){
    
	register_nav_menus(
		array(
			'top-menu' => __('Top Menu', 'webtegrity-framework'),
		)
	);
}
add_action('init', 'register_my_menus');

/***********************************************************************************************/
/* Add Theme Support */
/***********************************************************************************************/
if (function_exists('add_theme_support')) {
	
	add_theme_support('post-thumbnails', array('post'));
	//set_post_thumbnail_size(460, 460, true);
	add_image_size('custom-blog-image', 460, 460);

	add_theme_support('automatic-feed-links');
        
        add_theme_support( 'post-thumbnails' );

        add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list' ) );
}

/***********************************************************************************************/
/* Register Widgets */
/***********************************************************************************************/

// Regsiter Footer widget area
if (function_exists('register_sidebar')) {
	register_sidebar(array(
	'name' => 'Sidebar Widgets',
	'id'   => 'sidebar',
	'description'   => 'Display Widget Items in the Sidebar.',
	'before_widget' => '<div class="sidebar-widget col-lg-12 col-md-12 col-sm-12 col-xs-12">',
	'after_widget'  => '</div>',
	'before_title'  => '<h3>',	
	'after_title'   => '</h3>'
			));
}
// Regsiter Footer widget area
if (function_exists('register_sidebar')) {
	register_sidebar(array(
	'name' => 'Page Widgets',
	'id'   => 'page_sidebar',
	'description'   => 'Display Widget Items in the Page Sidebar.',
	'before_widget' => '<div class="sidebar-widget col-lg-12 col-md-12 col-sm-12 col-xs-12">',
	'after_widget'  => '</div>',
	'before_title'  => '<h3>',	
	'after_title'   => '</h3>'
			));
}
// Regsiter Footer widget area
if (function_exists('register_sidebar')) {
	register_sidebar(array(
	'name' => 'Blog Widgets',
	'id'   => 'blog_sidebar',
	'description'   => 'Display Widget Items in the Blog Sidebar.',
	'before_widget' => '<div class="sidebar-widget col-lg-12 col-md-12 col-sm-12 col-xs-12">',
	'after_widget'  => '</div>',
	'before_title'  => '<h3>',	
	'after_title'   => '</h3>'
			));
}
// Regsiter Footer widget area
if (function_exists('register_sidebar')) {
	register_sidebar(array(
	'name' => 'Footer Widget',
	'id'   => 'footer_widget',
	'description'   => 'Display Widget Items in the Footer.',
	'before_widget' => '<div class="footer-widget col-lg-4 col-md-4 col-sm-4 col-xs-12">',
	'after_widget'  => '</div>',
	'before_title'  => '<h3>',	
	'after_title'   => '</h3>'
			));
}

/***********************************************************************************************/
/* Register Scripts and Style */
/***********************************************************************************************/

// Register style sheet.
function webtegrity_scripts() {
	
	wp_enqueue_style( 'bootstrap_min_css', '//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css' );
        wp_enqueue_style( 'webteg_main_css', get_stylesheet_uri(), NULL, NULL, 'all' );
        wp_enqueue_script('jquery');
        wp_enqueue_script( 'masonry');
        wp_enqueue_script( 'double_tap', get_template_directory_uri() . '/js/scripts.min.js');

}

add_action( 'wp_enqueue_scripts', 'webtegrity_scripts' );

function load_google_fonts() {
	wp_register_style('googleRussoOne','http://fonts.googleapis.com/css?family=Russo+One');
        wp_enqueue_style( 'googleRussoOne'); 
        
	wp_register_style('googleOpenSans','http://fonts.googleapis.com/css?family=Open+Sans');
        wp_enqueue_style( 'googleOpenSans'); 

}
add_action('wp_print_styles', 'load_google_fonts');


remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'wp_generator' );
remove_action( 'wp_head', 'start_post_rel_link' );
remove_action( 'wp_head', 'index_rel_link' );
remove_action( 'wp_head', 'adjacent_posts_rel_link' );
remove_action( 'wp_head', 'wp_shortlink_wp_head' );

/*********************************************************************************/
/*How to automatically insert a list of related articles below the post*/
/*********************************************************************************/

function wptuts_more_from_cat( $title = "More From This Category:" ) {
    global $post;
    // We should get the first category of the post
    $categories = get_the_category( $post->ID );
    $first_cat = $categories[0]->cat_ID;
    // Let's start the $output by displaying the title and opening the <ul>
    $output = '<div id="more-from-cat"><h4>' . $title . '</h4><hr>';
    // The arguments of the post list!
    $args = array(
        // It should be in the first category of our post:
        'category__in' => array( $first_cat ),
        // Our post should NOT be in the list:
        'post__not_in' => array( $post->ID ),
        // ...And it should fetch 5 posts - you can change this number if you like:
        'posts_per_page' => 3,
        'orderby' => 'rand',
    );
    // The get_posts() function
    $posts = get_posts( $args );
    if( $posts ) {
        $output .= '<ul>';
        // Let's start the loop!
        foreach( $posts as $post ) {
            setup_postdata( $post );
            $post_thumb = get_the_post_thumbnail();
            $post_title = get_the_title();
            $permalink = get_permalink();
            $output .= '<li class="col-lg-4 col-md-4 col-sm-4 col-xs-12"><a href="' . $permalink . '" title="' . esc_attr( $post_title ) . '">' . $post_thumb . '</a><a href="' . $permalink . '" class="more-from-cat" title="' . esc_attr( $post_title ) . '">' . $post_title . '</a></li>';
        }
        $output .= '</ul><div class="clearfix"></div>';
    } else {
        // If there are no posts, we should return something, too!
        $output .= '<p>Sorry, this category has just one post and you just read it!</p>';
    }
    // Let's close the <div> and return the $output:
    $output .= '</div>';
    return $output;
}
Regsiter A Menu

What does it mean to register your menu? Well it is how WordPress connects their dashboard menu options with the menu area you have created in your code. If you go back over to Let’s Build A WordPress Theme From Scratch – Header.php you will notice I have set up the menu there. Even though it is there in the header.php file, nothing will work because you have to register it in the functions.php file with the code below. We start this function out by saying ‘function’ and then giving it a unique name. Here is says register_my_menus which is good because it tells you what you are doing in the function. If you happen to copy and paste this code below, and want to change the name, feel free to do so but remember that it is repeated in the add_action call at the bottom as well. Make sure those to areas match exactly or the function won’t work. The only other thing to change is where it says ‘Top Menu’. When you go into your dashboard and look under the Appearance tab, you will find the Menus tab. Here you can create a new menu or use one if it already exists, but if you want it to show up where you assigned this menu to go you have to click a checkbox that is under all of the menu pages. It should read Top Menu, which is assigning that menu to the menu area you coded in your header.php file. You can change the name by changing the label of ‘Top Menu’. The add_action call is what makes this function work…it says on initialization (‘init’) add the action of ‘register_my_menus’. Pretty simple right!

function register_my_menus(){
    
	register_nav_menus(
		array(
			'top-menu' => __('Top Menu', 'webtegrity-framework'),
		)
	);
}
add_action('init', 'register_my_menus');
Add Theme Support

Adding theme support is basically a way for you to tell WordPress to do something that it already supports in the core but doesn’t come standard / out of the box with. For example, you might not know this but you actually have to tell WordPress to support the ability for posts to have a featured image! You would think it just naturally has that capability but it doesn’t. So to activate this you simply use the add_theme_support function and pass in ‘post-thumbnails’ as it’s variable. You can see below that there are other things you can do as well like set your thumbnails to a specific size, create a custom image size that WordPress saves all your images to, and adding html5 support. You can find out more about these kinds of things from the WordPress Codex or just by searching around the web.

if (function_exists('add_theme_support')) {
        
        add_theme_support( 'post-thumbnails' );

	set_post_thumbnail_size(460, 460, true);

	add_image_size('custom-blog-image', 460, 460);

        add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list' ) );
}
Register A Widget Area / Sidebar

Widgetized areas in your WordPress website are a key perk to using WordPress at all. Most people create these widget areas in a sidebar, not always the case but for the most part they do. The best way to think of a widgetized area is to think of an area on your website where you can dynamically add content/widgets from your WordPress dashboard and have it appear on your website. To accomplish this we start with an if statement that basically tells WordPress that if the register_sidebar function exists then do the following. Inside that function we use the register_sidebar function to create our sidebar and pass in an array of items or parameters. First we give it a name, and the name is what you or the person using the dashboard will see at the top of this specific sidebar area under their Widgets Menu on their dashboard. Next we give it an id which no one really sees but you, however it is important to remember this id because you will need it to tell your php files where this sidebar should appear. Next you can give it a description which just tells you or your clients what to do with this sidebar/widget area in their dashboard. The before_widget and after_widget are exactly what they sound like. You can add html to be displayed before and after each widget. I use Twitter Bootstrap columns in this example, just to make sure each one is stacked on top of one another and not floating next to one another. The same can be done with the title of the widget by using before_title and after_title. One you upload your functions.php file, you should see this new area in your Widgets dashboard area.

if (function_exists('register_sidebar')) {
	register_sidebar(array(
	'name' => 'Sidebar Widgets',
	'id'   => 'sidebar',
	'description'   => 'Display Widget Items in the Sidebar.',
	'before_widget' => '<div class="sidebar-widget col-lg-12 col-md-12 col-sm-12 col-xs-12">',
	'after_widget'  => '</div>',
	'before_title'  => '<h3>',	
	'after_title'   => '</h3>'
			));
}
Enqueuing Stylesheets And Scripts

I wrote another article called Link Scripts and Stylesheets Correctly in WordPress so I will tell you to go check it out so I don’t have to repeat the information again. After you are caught up there, look back at the above code because I show you how to load Google Fonts properly and also how to remove standard scripts that you might not need that come with the WordPress core or from other plugins.

Advanced Example – Related Posts on Single Post Page

This is a pretty advanced example of code that can be written in your functions.php file to create some amazingly dynamic things happen. This example is from WPTuts and basically adds other posts that are in the same category as the one that you are viewing to show up at the bottom of that page for cross marketing. Think of this code as where you want to be when you grow up. It is pretty advanced for most people but once you really dig into it and study it you will learn that it is actually pretty easy to understand once you take the time to lay it out and play with it on a site.

function wptuts_more_from_cat( $title = "More From This Category:" ) {
    global $post;
    // We should get the first category of the post
    $categories = get_the_category( $post->ID );
    $first_cat = $categories[0]->cat_ID;
    // Let's start the $output by displaying the title and opening the <ul>
    $output = '<div id="more-from-cat"><h4>' . $title . '</h4><hr>';
    // The arguments of the post list!
    $args = array(
        // It should be in the first category of our post:
        'category__in' => array( $first_cat ),
        // Our post should NOT be in the list:
        'post__not_in' => array( $post->ID ),
        // ...And it should fetch 5 posts - you can change this number if you like:
        'posts_per_page' => 3,
        'orderby' => 'rand',
    );
    // The get_posts() function
    $posts = get_posts( $args );
    if( $posts ) {
        $output .= '<ul>';
        // Let's start the loop!
        foreach( $posts as $post ) {
            setup_postdata( $post );
            $post_thumb = get_the_post_thumbnail();
            $post_title = get_the_title();
            $permalink = get_permalink();
            $output .= '<li class="col-lg-4 col-md-4 col-sm-4 col-xs-12"><a href="' . $permalink . '" title="' . esc_attr( $post_title ) . '">' . $post_thumb . '</a><a href="' . $permalink . '" class="more-from-cat" title="' . esc_attr( $post_title ) . '">' . $post_title . '</a></li>';
        }
        $output .= '</ul><div class="clearfix"></div>';
    } else {
        // If there are no posts, we should return something, too!
        $output .= '<p>Sorry, this category has just one post and you just read it!</p>';
    }
    // Let's close the <div> and return the $output:
    $output .= '</div>';
    return $output;
}

Conclusion

Like I mentioned before, the functions.php file is super useful and can really be tailored to drive some pretty big sites. Take some time to go out and find some other blogs giving you different types of code to add to your functions file so you can further get accustomed to what to expect in this file and what can grow your development arsenal. I will be posting only one more article in this tutorial series and it will be about the MOST IMPORTANT FILE OF THEM ALL…style.css.

Team Treehouse – Learn PHP for WordPress

If you are serious about learning to develop custom themes in WordPress, I highly recommend you join Team Treehouse. They have a full video course on everything WordPress development, including a course on specifically writing PHP for WordPress.