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_script
function 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
.