If you want to include an external PHP file inside your template (or code), then put that code inside another template (called, say, mycode.php). Put that mycode.php file in your theme folder.
Then you can get_template_part('mycode')
. Note that you do not include the '.php' part as the parameter of get_template_part.
Your code in mycode.php will be executed at the point of the get_template_part call. Note that this is a good way to include an external functions call that is only needed by a template.
Added
More experimentation on how to 'include' a file that has functions inside your template. I learned that the locate_template
command is better in all cases. get_template_part
may not happen 'soon' enough for your page.
So I now use
locate_template("myfunctions.php",true,true);
where the myfunctions.php
is located in the active theme folder. The two 'true' parameters ensure that the file is loaded at the proper time. The first 'true' will load the file if found. The second 'true' will use require_once
instead of a require
.
My use of this was in a template. I needed some functions that would add things to the head (with an apply_filter('wp_head')
). The functions are in the my_functions.php
file. So the template contains the locate_template
first, then the filters for the wp_head
after.
This is a clever and useful way to get a file of your functions to load with a template, while not requiring the functions to be available globally - just in your template.