Adding JS to WordPress effortlessly with Code Snippets

I’ve been using Code Snippets to keep my PHP additions organized, but I also had a lot of javascript files being enqueued in my theme’s functions.php file. This meant that they were likely to disappear on my next theme update or switch. I could have used a simple JS plugin like JavaScript AutoLoader, but I wanted more control over when certain scripts were used, for example with the is_product() function in WooCommerce.

So I started enqueuing my scripts in a snippet with Code Snippets:

add_action( 'wp_footer', function () { ?>
<script>
/* Loose js for footer can go here */
</script>
<?php } );

function load_our_lovely_js_please() {
    if (is_product()) {
        wp_enqueue_script('prodscript','https://mastersonmethodequinetherapy.com/wp-content/themes/Avada/js/product.js', false, '1.0', true );
    }
}

add_action( 'wp_enqueue_scripts', 'load_our_lovely_js_please' );

In the first half of this snippet there is a place for putting straight javascript into the page, and later on we have a chance to add external js files. I also used a fluffy function name to avoid colliding with other loader functions being used, which may or may not be necessary. Note that I don’t add the opening <?php tag at the start of this snippet, as per Code Snippets’ workflow.

I didn’t have luck using the is_product() function to determine when I should call add_action(), so I’m using it inside my loader function and it works fine on wp_enqueue_script(). Perhaps when add_action() is called, the system doesn’t know if we are on a product page yet? In any case, using it inside my loader function allows me to have just 1 loader function with my loading decisions inside:

add_action( 'wp_footer', function () { ?>
<script>
/* Loose js for footer can go here */
</script>
<?php } );

function load_our_lovely_js_please() {
    wp_enqueue_script('beeboo','https://mastersonmethodequinetherapy.com/wp-content/js/beeboo.js', false, '1.0', true );
    if (is_product()) {
        wp_enqueue_script('prodscript','https://mastersonmethodequinetherapy.com/wp-content/js/product.js', false, '1.0', true );
    }
}

add_action( 'wp_enqueue_scripts', 'load_our_lovely_js_please' );

This way of doing it was patched together from some answers given by Code Snippets’ author Shea Bunge in the WP Plugin support section. Thanks Shea! I opted to use add_action() instead of just wp_enqueue_script() by itself, because that didn’t seem to work in this case.

If you’ve got a better way of managing and enqueuing JS, please let me know!