skip to Main Content

How do I load a script if a PHP condition is true?

For example, I got an external script called script.js and I wanna load this if it’s on the product page of WooCommerce.

I’ve tried the following but it doesn’t work because it prints the code on the page:

<?php 
add_action( 'template_redirect', 'check_product_page' );

function check_product_page() {
   if(is_product()) {
      include ('script.js');
   }
}
?>

If I write the script inside a PHP like the below, it causes a fatal error:

<?php 

echo
'<script type="text/JavaScript"> 
   window.addEventListener("load", function() {
      //some code here...
   })
</script>';
?>

3

Answers


  1. Try this:

    <?php
    if($condition == true){ 
      echo '<script type="text/javascript" src="script.js"></script>';
    }
    ?>
    

    or:

    <?php if($condition == true): ?>
      <script type="text/javascript" src="script.js"></script>
    <?php endif; ?>
    
    Login or Signup to reply.
  2. Actually this works on my side, checkout maybe you have another issue:

        echo '<script type="text/JavaScript"> 
       window.addEventListener("load", function() {
          //some code here...
       })
    </script>';
    
    Login or Signup to reply.
  3. It’s because the single quotes are inside your string. You should actually do it the way which other people have shown, but if you need it to be an inline script you can do it like this:

    <?php
       //some php can go here..
    ?>
    <script type="text/JavaScript"> 
       window.addEventListener("load", function() {
          //some code here...
       })
    </script>
    <?php //more php can go here... ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search