'How to embed a JS script on a specific WooCommerce product page
I've got a JS code that gives us a product stock amount from another provider for our client.
But how do I embed the JS jQuery on a single WooCommerce product?
var settings = {
"url": "https://www.URL.com",
"method": "GET",
"timeout": 0,
"headers": {
"client-secret": "password123"
},
};
$.ajax(settings).done(function (response) {
console.log(response);
});
Tried adding it to our theme's header script but with no success.
No experience with JS so any help is greatly appreciated.
Our provider mentioned it's required to be in the header, if that matters. Also is it possible to add an if $product string to only apply this script to certain products? We'd only need this script running on a handful of products.
Solution 1:[1]
You can add the JS script via the wp_footer hook and use the is_product() conditional tag to insert the code only on the WooCommerce product page.
// It adds a JS script only on the WooCommerce product page.
add_action( 'wp_footer', 'add_script_to_product_page' );
function add_script_to_product_page() {
// Only on the product page.
if ( ! is_product() ) {
return;
}
?>
<script type="text/javascript">
var settings = {
"url": "https://www.URL.com",
"method": "GET",
"timeout": 0,
"headers": {
"client-secret": "password123"
},
};
$.ajax(settings).done(function (response) {
console.log(response);
});
</script>
<?php
}
The code has been tested and works. Add it to your active theme's functions.php file.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vincenzo Di Gaetano |
