Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Stephen O'Connor
Stephen O'Connor
22,291 Points

Conditionally Load JavaScript in WordPress

I have a question about conditionally loaded JavaScript in WordPress. I have used the following code to load certain scripts on only the pages they need to be loaded on, but I have come across a strange issue that I cannot seem to get my head around except by adding the conditional statement to my footer.php file, which is annoying me slightly because it is not the correct way of enqueuing scripts.

Currently in my functions.php file I have

function theme_js() {
    if( is_front_page() ) {
        wp_enqueue_script( 'cookie-js', get_template_directory_uri() . '/assets/js/js.cookie.js', array( 'jquery' ), '', true );
        wp_enqueue_script( 'covervid-js', get_template_directory_uri() . '/assets/js/covervid.min.js', array( 'jquery' ), '', true );
        // more scripts etc but you get the idea
    }
}
if( !is_admin() ) {
    add_action( 'wp_enqueue_scripts', 'theme_js' );
}

The site has a custom post type called 'Portfolio' and has single portfolio items, these portfolio items can either be portfolio items with a hero image or portfolio items with a hero video and the template for displaying these portfolio items is the same template, single-portfolio.php. So in this template I have a fair few conditionals to load certain custom fields and data depending on the portfolio item type - image or video - but the video pages need additional JavaScript to make the hero videos fit their container and a few other things, but I can't seem to figure out how to conditionally load this JavaScript in my functions.php file. I know I can use if(is_page('page-name or id')) but I don't want to do that because everytime I add a new video to the portfolio i will need to add another conditional to the functions.php file.

So at the moment I have the following code in my footer.php file:

<?php
    $project_type = get_field('project_type');
?>
<?php if ($project_type == 'Video') : ?>
    <script src="<?php bloginfo('stylesheet_directory'); ?>/assets/js/video-specifics.js"></script>
<?php endif; ?>

Which loads the video script depending on the project type - which is a custom field (radio button) in the project publish page.

Can I just add this code to my functions.php file? I'm not sure if that would work or not...

Sorry for the long question, it works at the moment but I'd rather not add the conditional to my footer.php file as it feels a bit 'hacky'.

Any insight would be appreciated.

Thanks.

1 Answer

Kevin Korte
Kevin Korte
28,149 Points

Instead of using is_page() why not use is_page_template()? I think this should work:

<?php
function theme_js() {
    if( is_front_page() ) {
        wp_enqueue_script( 'cookie-js', get_template_directory_uri() . '/assets/js/js.cookie.js', array( 'jquery' ), '', true );
        wp_enqueue_script( 'covervid-js', get_template_directory_uri() . '/assets/js/covervid.min.js', array( 'jquery' ), '', true );
        // more scripts etc but you get the idea
    }
    if( is_page_template( 'single-portfolio.php' )) {
      wp_enqueue_script( 'video-specifics', get_template_directory_uri().'/assets/js/video-specifics.js',array('jquery'),'',true );
    }
}
if( !is_admin() ) {
    add_action( 'wp_enqueue_scripts', 'theme_js' );
}

You can of course adjust the enquese script I added as needed, but if both the image and the video single portfolio use the same template, I think this will work. It's untested, but try it and let us know.

https://codex.wordpress.org/Function_Reference/is_page_template

Stephen O'Connor
Stephen O'Connor
22,291 Points

Kevin, thanks for your response. Would this not load video-specifics.js to both the image and the video portfolio pages? I only need to load video-specifics.js when the portfolio piece is a video and not load it when it is an image. Hope this makes sense.

Kevin Korte
Kevin Korte
28,149 Points

Yes it would, I didn't think of that. How big is the extra JS file? Just curious which is faster, loading the JS file on both video and image portfolio pages, or running the extra conditionals to figure it out. I'd benchmark test both with your dev inspector and go from there. In any event, I hate posting untested code, but I don't have an easy way to test this code first, so I'm building just off of documentation, maybe this in your functions.php?

<?php
if( is_page_template( 'single-portfolio.php' )) {
    global $post
    $project_type = get_field('project_type', $post->ID);
    if( '$project_type' == 'Video' ) {
      wp_enqueue_script( 'video-specifics', get_template_directory_uri().'/assets/js/video-specifics.js',array('jquery'),'',true );
    }
}
Stephen O'Connor
Stephen O'Connor
22,291 Points

If I load my video-specifics.js file in a non video page it throws out a console error - Uncaught TypeError: Cannot read property 'parentNode' of undefined - that's why I want to conditionally load it only on the video pages. Unless I am structuring my js completely wrong... I have all my javascript calls inside either a document.ready or a window.load and have only the javascript used on each page loading at any one time. I could direct you to a test site if that would help me explain things further.

I could give this a go and see if it works, I thought there must be a better way to do this than to have lots of different conditionals to only load certain scripts on certain pages that need them.

Thanks.