WordPress: Dynamically Include JavaScript or PHP Using the Post ID
One of the efforts that I’ve really been working on this year on Martech Zone is providing some simple web applications that are helpful to our visitors. There’s some basic development behind these that include both PHP and JavaScript (mostly jQuery).
With WordPress, there’s not a really convenient way to write pages or posts with the specific code that you want in the header, though. I don’t want the code site-wide and don’t want to slow my site down with a gigantic script file.
When I first started writing the apps, I was doing it all in functions.php of my child theme and using is_single with the post ID number. After quite a few apps, though, my functions.php file began to get quite unruly.
A nifty solution that I came up with using the WordPress API was to add a apps directory to my child theme whose contents are read. When the filename matches the post ID, it includes the JavaScript and/or PHP file based on the file’s extension. Some of my apps have custom PHP, some just JavaScript, and some have both. This script works for any scenario!
function include_app_file() {
// Check if this is a single post
if (is_single()) {
// Get the file path of the “apps” subdirectory from the transient cache
$apps_dir = get_transient(‘apps_dir’);
// If the cache is empty, get the file path and store it in the cache
if (false === $apps_dir) {
$apps_dir = get_stylesheet_directory() . ‘/apps/’;
set_transient(‘apps_dir’, $apps_dir, 3600);
}
// Construct the file names based on the post ID
$js_file_name = get_the_ID() . ‘.js’;
$php_file_name = get_the_ID() . ‘.php’;
// Check if the JS file exists
if (file_exists($apps_dir . $js_file_name)) {
// If the JS file exists, include it in the head section of the page
wp_enqueue_script(get_the_ID(), get_stylesheet_directory_uri() . ‘/apps/’ . $js_file_name, array(), null, true);
}
// Check if the PHP file exists
if (file_exists($apps_dir . $php_file_name)) {
// If the PHP file exists, include it
include($apps_dir . $php_file_name);
}
}
}
add_action(‘wp_head’, ‘include_app_file’);