I am trying to develop a Wordpress theme which requires a lot of PHP functions and custom classes.
I am wondering the best practice for including additional PHP files within Worpdress. Example: Do I list every file to include using:
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.
Thanks in advance for your help :)
Include will include the file content
Require will throw an error if file not found.
Include_once .. check if included if no then include
Require_once same as include_once but with error if file not found
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.
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.
require get_template_directory() . '/inc/template-tags.php';
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()