I have been working with WordPress for a while and one thing that irritates me is that the functions.php contains a lot of codes. This makes the file looks messy and hard to follow. There are some methods to improve this, which I have learnt from KnowTheCode to make this file looks cleaner. Briefly what I do:
- Break one functions.php file into smaller files based on the purposes. Save them in a functions folder.
- Define constants to save computing time.
- Add a config.php file to store enqueued JS and CSS.
Let’s go into details.
Break functions.php into smaller files based on the purposes
So this is quite straight forward. I just categorized the functions into smaller purposes. Depending on your theme and your functions it will look different than mine. Here are the categories that I come up with:
- styles-scripts-fonts.php: Enqueue styles, scripts and fonts.
- custom-post-types.php: Defines and functions for custom post types.
- post.php: functions used on blog posts (e.g query latest posts, get related posts, etc.).
- remove-scripts.php: WordPress has lots of unnecessary functions that I don’t use and this file shut it down for better web speed.
- third-parties: for example Google Tag Manager scripts installed.
I will not go into the details of each file here because your case will be totally different than mine. Just make sure that you analyze the functions before making a file for each. After categorizing scripts into the right file, let’s include them in the functions.php:
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) exit;
include_once 'functions/styles-scripts-fonts.php';
include_once 'functions/custom-post-types.php';
include_once 'functions/post.php';
include_once 'functions/remove-scripts.php';
include_once 'functions/third-parties.php';
Now it looks much cleaner!
Define constants to save computing time
Defining constants saves computing time. For example, the get_stylesheet_directory_uri() will be defined into a constant, so that whenever the theme needs, it does not need to do the whole process before getting the result.
define ( 'CHILD_THEME_DIR', get_stylesheet_directory_uri() );
So instead of looking for and implement this function in the theme, now only a string will need to be retrieved. When enqueueing styles and scripts, this constant will be called all the time.
The second thing that can be defined is the theme version.
$the_theme = wp_get_theme();
define ( 'THEME_VERSION', $the_theme->get( 'Version' ));
The last constant is a list of three latest posts because they are written in the footer section of the website. So I think making them into an array constant will make website faster than querying them all over again.
define ( 'THREE_LATEST_POSTS', ak_query_latest_posts(3) );
And in the post.php, the function will look something like:
// Query latest blog posts
function ak_query_latest_posts($number_of_posts) {
$posts = array();
$args = array(
'numberposts' => $number_of_posts,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish'
);
$recent_posts = wp_get_recent_posts($args);
if(is_wp_error($recent_posts) || empty($recent_posts)) return;
foreach ( $recent_posts as $recent ) {
$single_post = array(
'link' => get_permalink($recent['ID']),
'title' => $recent['post_title'],
'thumb' => get_the_post_thumbnail_url($recent['ID']),
);
$posts[] = $single_post;
}
wp_reset_query();
return $posts;
}
Add a config.php file to add/remove enqueued styles and scripts
It’s not comfortable to repeat all the time the wp_enqueue_style() and wp_enqueue_script(). So there should be a file that contains all the styles and scripts with configuration. Then, in the styles-scripts-fonts.php file it will loop through all the items and add them accordingly.
// This file contains configuration for CSS, JS and fonts
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly.
$fonts = array(
'body-fonts' => array(
'src' => 'https://fonts.googleapis.com/css?family=Montserrat:400,700|Work+Sans:300,400,700',
'page_template' => null,
),
'fontawesome' => array(
'src' => 'https://use.fontawesome.com/releases/v5.1.0/css/all.css',
'page_template' => null,
),
);
$css = array(
'main-styles' => array(
'src' => CHILD_THEME_DIR . '/css/main.min.css',
'page_template' => null,
'version' => '6.4.0'
),
'lity-css' => array(
'src' => CHILD_THEME_DIR . '/css/lity.min.css',
'page_template' => array(
'page-templates/some-page.php',
'page-templates/video-tutorials.php',
'page-templates/webinars.php',
),
'version' => '0.1'
),
'cocoen-css' => array(
'src' => CHILD_THEME_DIR . '/css/cocoen.min.css',
'page_template' => 'page-templates/gallery-page.php',
'version' => '0.1'
)
);
$js = array(
'lity-js' => array(
'src' => CHILD_THEME_DIR . '/js/lity.min.js',
'page_template' => array(
'page-templates/video-tutorials.php',
'page-templates/some-page.php'
),
'defer' => '',
'in_footer' => true,
'version' => '1'
),
'cocoen-js' => array(
'src' => CHILD_THEME_DIR . '/js/cocoen.min.js',
'page_template' => 'page-templates/gallery.php',
'defer' => '',
'in_footer' => false,
'version' => '1.2'
),
'main-scripts' => array(
'src' => CHILD_THEME_DIR . '/js/main.min.js',
'page_template' => null,
'defer' => '#defer',
'in_footer' => true,
'version' => '5.4.4'
)
};
You can see that the constants CHILD_THEME_DIR and THEME_VERSION are used quite often.
Here comes the styles-scripts-fonts.php:
add_action( 'wp_enqueue_scripts', 'ak_theme_enqueue_styles' );
/**
* Enqueue css and js filtered by pages
* To add or remove file, do it in functions/config.php
*/
function ak_theme_enqueue_styles () {
wp_enqueue_script('jquery');
include_once 'config.php';
foreach ($fonts as $handle => $value) {
if($value['page_template'] == null) {
wp_enqueue_style($handle, $value['src'], array(), null);
}
else {
if (is_page_template($value['page_template'])) {
wp_enqueue_style($handle, $value['src'], array(), null);
}
}
}
foreach ($css as $handle => $value) {
if($value['page_template'] == null) {
wp_enqueue_style($handle, $value['src'], array(), $value['version']);
}
else {
if (is_page_template($value['page_template'])) {
wp_enqueue_style($handle, $value['src'], array(), $value['version']);
}
}
}
foreach ($js as $handle => $value) {
if($value['page_template'] == null) {
wp_enqueue_script($handle, $value['src'] . $value['defer'], array(), $value['version'], $value['in_footer']);
}
else {
if (is_page_template($value['page_template'])) {
wp_enqueue_script($handle, $value['src'] . $value['defer'], array(), $value['version'], $value['in_footer']);
}
}
}
}
Note: So when adding script/style into config.php, there is page_template required. This prevents the item to display in pages where they are not needed. For example, the cocoen is only needed for the gallery page, there is no idea to include them (two .js files and one .css file) to every page. This will make the website loads faster due to decrease in HTTP requests.
Conclusion
There will be many other effective ways to make the functions.php less messy and above are just a few. Thanks for reading and I hope this post is helpful to you.