WordPress Conditional Javascript Include

I am trying to conditionally include javascript files on specific pages in wordpress. I finally found a snippet of code that does exactly what I want but it doesn’t seem to be working. Any thoughts? I didn’t include the real page names but I am using the page slug.

<?php if (is_page(array('page-slug','page-slug','page-slug'))) { ?>
   <script src="<?php echo get_template_directory_uri(); ?>/js/script.js"></script>
<? } else { ?>
   <script src="<?php echo get_template_directory_uri(); ?>/js/script.js"></script>
   <script src="<?php echo get_template_directory_uri(); ?>/js/conditional-script.js">    </script>
<? } ?>

I Put this code where I call the rest of my scripts in my custom template files.

Related posts

Leave a Reply

1 comment

  1. On third last line and last line, it looks like you are using <? to open the line. Try using <?php instead. So, it should be:

    <?php
    if (is_page(array('page-slug','page-slug','page-slug'))) 
    { ?>
        <script src="<?php echo get_template_directory_uri(); ?>/js/script.js"></script>
    <?php
    } 
    else 
    { ?>
        <script src="<?php echo get_template_directory_uri(); ?>/js/script.js"></script>
        <script src="<?php echo get_template_directory_uri(); ?>/js/conditional-script.js"></script>
    <?php
    }
    ?>
    

    And as I mentioned, I would recommend enqueuing scripts in the future 😉