Enqueue script o style only if a template part is loaded

I have registered some styles and scripts that should be loaded if a template part is loaded in a template file. For ex:

in home.php

<?php get_template_part( 'template-parts/external_links'); ?>

(this template-part is loaded across different template files) therefore, I want to enqueue (a previously registered file in functions.php)

Using template files for example I use:

if(is_page_template('admin.php')){
        wp_enqueue_script( 'unicorn-admin');
    }

Is there a way to enqueue a file when get_template_part( ‘template-parts/external_links’); is used?

3 Answers
3

You can use the get_template_part_{$slug} hook, which fires before a template part is loaded. You can find the reference here, which I find more useful than the official reference.

So, I tested it in the twentytwentyone theme (yes I modified the theme directly but only for testing). I tested it with the template-parts/content/content-single.php part, and I created a test.js file, with an alert inside it, in the assets/js/ folder of the theme. Then, I placed the following code in functions.php.

function test_template_part_hook($slug, $name, $args) {
    wp_enqueue_script('test', get_template_directory_uri() . '/assets/js/test.js', array('jquery'));
}

add_action( 'get_template_part_template-parts/content/content-single', 'test_template_part_hook', 10, 3 );

And the alert triggers in every single post, of course, you should modify the above code with your own paths to your files and complete the wp_enqueue_scriptfunction with the rest of the arguments that function uses.

So, basically what you need to do is what is described above, using get_template_part_slug as the action name, where slug is the path of the template part file you want to use, in your case, for what I read in you question, slug = 'template-parts/external_links', so the entire hook name should be get_template_part_template-parts/external_links.

Leave a Comment