Creating a WordPress theme Part 6 – Custom functions file

This series is about how to create and develop a WordPress blog theme in 2021 using the correct methods and techniques.

Part 6 is the custom functions file. Part 5 building the comments section. Part 4 was the single post page. Part 3 included settings values, The WordPress loop and pagination. Part 2 was splitting the theme into different sections as well as theme naming and details. Part 1 was the installing and setup of WordPress and base theme.

creating WordPress theme

For this guide you will need a local webserver with PHP and MySQL, I will be using XAMPP and HeidiSQL for this series.

Theme functions file

In a themes directory exists the functions.php file. This file contains custom functions that are only active when the theme is. These custom functions could be widgets or custom sections for your theme.

The loading of the functions.php file is automatic, you do not have to reference it anywhere.

An example is:

functions.php

<?php
function show_date_time()
{
    echo date('Y-m-d H:i:s');
}

In footer.php under the copyright text:

<p class="text-muted text-center"><?php show_date_time();?></p>

This will output the current datetime in the footer

WordPress creating theme functions file exampleBe very careful not to use a WordPress native function name in your functions file as this can cause your website to not load.

The add action

Immediatley after the function you can add an add_action(), this will hook the function to an action.

A good example for this is an action for when you publish a post:

add_action('publish_post', 'send_post_tweet');

Send a Tweet with the send_post_tweet function when the publishpost action occurs.