I am trying to develop a WordPress theme which requires a lot of PHP functions and custom classes.
I am wondering what the best practice is for including additional PHP files within WordPress. Example: Do I list every file to include using:
- include();
- require_once()
- etc
When I review other developers themes I never stumble across a batch of “include() statements, so I believe I must be missing some standard method of performing these includes.
You can follow any method. But I suggest you to use
require
to include any file._s ( aka underscores ) which is theme starter kit and default themes of WordPress such as TwentyFourteen, TwentyThirteen, etc are using
require
to include files.See sample code used in TweentyFourteen theme.
If you are using child theme and need to load php file from child theme folder, you should use
get_stylesheet_directory()
function. get_stylesheet_directory()So if you are the one who wrote the file you should include .. not include_once.
We usually, use include for unnecessary files. Require for important files. For example footer.php will not make script stop .. but core.php is important.
Why not put all the included files into a single file (library.php) and include that in your theme? By doing this if you need to change something you can change just one file. Also you can use conditional tags like if..else within the library.php to include specific files for certain pages.
I would also suggest that you use require_once() for important files so you get an error if the file is missing. If there is no error when a file is missing then functions that use that file will through multiple errors.
Also as @Othman has suggested you can use include for less important files.
Another method would be assigning a
file and include it into your functions.php to avoid redundancy
For Example my functions.php in my root folder
where i get my files from the /inc dir and the functions dir/
There is also another method on the wordpress codex
https://codex.wordpress.org/Theme_Development#Including_Template_Files
Also checkout the wordpress organizing theme files docs
https://developer.wordpress.org/themes/basics/organizing-theme-files/