One way to do this is by looking for shortcodes in pages that need these scripts and then load these scripts into the page. You can use the built-in
has_shortcode()
function in your PHP files to look for these specific shortcodes.
In the example below, we have added a shortcode in the functions.php file called
test_custom_shortcode
and another function to enqueue a script called test.js. The second function only triggers the enqueue function when it serves a page that has the test_custom_shortcode
in the post.
function test_custom_shortcode_callback() { echo 'Cool post!
'; } add_shortcode( 'test_custom_shortcode', 'test_custom_shortcode_callback' ); function enqueue_test_script() { global $post; if(!$post){ return false; } if( has_shortcode( $post->post_content, 'test_custom_shortcode' )) { wp_register_script('test_script', get_stylesheet_directory_uri() . "/test.js" ); wp_enqueue_script('test_script'); } } add_action( 'wp_enqueue_scripts', 'enqueue_test_script' );
We can see here in the images below the enqueued script is running well on the console only on the pages where the shortcode exists.
Other pages won't load the script thus you won't be able to find the script on these pages.