Smart functions.php in WordPress: Split It Into Files

Quick Summary
- Move groups of theme functions into files in an includes folder and keep functions.php as a short list of require_once lines.
- A missing file makes require_once stop with a fatal error, so use it for essential code, while include only shows a warning.
- The relative paths depend on PHP's include path, so build full paths with get_template_directory(), or get_stylesheet_directory() in a child theme.
A WordPress theme’s functions.php can grow into hundreds of lines of setup code, script loading, custom post types and shortcodes. A tidier approach is to split that code into small files by topic and keep functions.php as a short list that loads them.
Create an includes folder inside your theme, move each group of functions into its own file there, and replace the contents of functions.php with lines like these:
<?php
include 'includes/options-page.php';
require_once 'includes/wp_bootstrap_navwalker.php';
require_once 'includes/theme_inits.php';
require_once 'includes/theme_enqueue.php';
require_once 'includes/theme_cpt_job.php';
require_once 'includes/theme_functions.php';
require_once 'includes/theme_sidebar.php';
require_once 'includes/theme_extras.php';
require_once 'includes/theme_shortcodes.php';
require_once 'includes/gf_options.php';
?>How it works
Each line loads one file from the includes folder. The file names show what goes where in this example theme: theme setup, enqueued scripts and styles, a job custom post type, sidebars, shortcodes, a Bootstrap navigation walker and an options page. Rename the files and the list to fit your own project.
require_oncestops with a fatal error if the file is missing, and never loads the same file twice. Use it for code the theme can’t work without.include, used here foroptions-page.php, only shows a warning if the file is missing, and the site keeps running.- The paths are relative, so PHP resolves them through its include path. To make them independent of that, build the full path with
get_template_directory()followed by/includes/and the file name. In a child theme, useget_stylesheet_directory()for files that live in the child theme; child vs parent theme path functions explains the difference. - If a file runs code as soon as it loads and that code needs something from another file, load the other file first.
Related articles
- a scalable WordPress project structure: the same one-concern-per-file idea applied to a whole theme
- setting up a custom post type with register_post_type(): the kind of code a file like theme_cpt_job.php holds

