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>';
?>
CodePudding user response:
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; ?>
CodePudding user response:
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>';