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
Try this:
or:
Actually this works on my side, checkout maybe you have another issue:
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: