Approach 1
Use the body class. all templates will have a class representing them. ie: body.archive
, body.single
, body.home
, etc. It will even have specific tax/post type classes for more granular control. Wrap your js function in something that checks for that body class. The following should do the trick:
jQuery
if ( $( 'body' ).first().hasClass( 'archive' ) ) {...}
Plain JS
const body = document.querySelector('body');
if ( body.classList.contains('archive') ) {...}
Note: Body classes may be tweaked to your needs via the body_class
filter, and the body_class()
function must be on your body element.
Function (make sure this is on your body element):
body_class() | Function | WordPress Developer Resources
https://developer.wordpress.org/reference/functions/body_class/
Filter (Use this to manipulate):
body_class | Hook | WordPress Developer Resources
https://developer.wordpress.org/reference/hooks/body_class/
Approach 2
You could also target this template in php and wrap your wp_enqueue_script
for this file (as long as that is all that is in this file, and you need nothing else) in a conditional to check, ie: is_archive()
, is_single()
, is_home()
.
If you bundle your assets, use the first approach.