In a template, I have a need to include_once
an external PHP (an include.php
) that contains functions that I need to use inside the template.
Included in those functions are CSS styles and an external JS script.
The CSS is inside a function in the include.php. And the JS script also needs to be in the area.
So I need to include_once("includes.php")
(which is in the theme's root folder). I figured I would use code similar to this:
add_action('wp_head', 'fst_include',20);
function fst_include() {
include_once get_stylesheet_directory(). "/includes.php"; // load required functions
return;
}
Since the action is 'wp_head', that should get the include_once("includes.php")
in the head area. I use get_stylesheet_directory
because the includes.php file will be in a Child Theme.
Once that is loaded, then I can add some CSS with this:
add_action('wp_head', 'more_css',30) // 'more_css' is a function inside the includes.php file that contains some CSS
And add some JS with
add_action('wp_head', 'some_script',30) // 'some_script' is a function inside the includes.php file that adds some JS
I give the last two add_actions a priority of '30' so they will be loaded after the includes.php file is loaded. (Because the includes.php has a priority of 20.)
But the includes.php file doesn't appear to be loading, as the 'some_script' function (contained in includes.php) is not available, and causes an error.
So I need a way to add a include_once('includes.php')
so that the functions inside there are available 'later' in the template. I don't think that get_template_part
is appropriate because the include_once
needs to be in the section.
Added - But Why?
Why do I need to do this? My template displays a form. The form's code and functions are in the include.php file. Even the form is displayed by a function in the include.php.
The include.php file is a 'package' of functions and scripts and actions and changing of DOM elements to perform specific functions when the form is displayed - and the user fills out the form and submits it. (The 'package' is the process that is used to protect forms - like contact forms - against spam-bots. It's an effective process, but a bit complex. If you are really interested, you can go here to learn about it.)
The include.php file is also built as a standalone/non-WP code that can be used on non-WP pages. I don't want to maintain two versions of the code.
The form has to 'live' in the visual look of whatever theme is being used, if used on a WP site. I figured a template would be the best way to do that. So I need to get my include.php 'inside' the template so that it's functions can be called.
As for the priorty used in the add_action, that was an attempt to make sure that the include.php file is included in the area so that I can call the function that includes the CSS used for the form. If include.php is not loaded first, then the CSS-calling function will fail.