I have a simple piece of "hello world" code I'm trying to execute on a page. I'm adding it using a PHP snippet:
add_action( 'wp_head', function () { ?>
<script type="text/javascript" src=".2.1/jquery.min.js">
jQuery(document).ready(() => {
jQuery('div#tm-extra-product-options').click(() => {
console.log("it's working!")
});
});
</script>
<?php } );
I can get it to show up in the page source and if I paste that directly into the console it works fine, however when I load the page and try it, I get nothing. I know that jQuery is loading because it is defined in the console without my intervention (previously this was not the case), however the code itself appears to not work at all.
I have a simple piece of "hello world" code I'm trying to execute on a page. I'm adding it using a PHP snippet:
add_action( 'wp_head', function () { ?>
<script type="text/javascript" src="https://ajax.googleapis/ajax/libs/jquery/3.2.1/jquery.min.js">
jQuery(document).ready(() => {
jQuery('div#tm-extra-product-options').click(() => {
console.log("it's working!")
});
});
</script>
<?php } );
I can get it to show up in the page source and if I paste that directly into the console it works fine, however when I load the page and try it, I get nothing. I know that jQuery is loading because it is defined in the console without my intervention (previously this was not the case), however the code itself appears to not work at all.
Share Improve this question asked Apr 20, 2020 at 2:20 fudgefudge 1173 bronze badges 3 |2 Answers
Reset to default 0Try this.
add_action ( 'wp_head', 'custom_script_hook');
function custom_script_hook() {
?>
<script type="text/javascript" src="https://ajax.googleapis/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
$output='<script>
jQuery(document).ready(() => {
$("div#tm-extra-product-options").click(() => {
console.log("it working!")
});
});
</script>';
echo $output;
}
It is always an headache working with jQuery in Wordpress. Just try replace second jQuery with $ sign. I guess once you opened jQuery tag you need to continue with $ sign inside: Like this
add_action( 'wp_head', function () { ?>
<script type="text/javascript" src="https://ajax.googleapis/ajax/libs/jquery/3.2.1/jquery.min.js">
jQuery(document).ready(() => {
$('div#tm-extra-product-options').click(() => {
console.log("it's working!")
});
});
</script>
<?php } );
div#tm-extra-product-options
? Are you certain that it's the correct selector? – Jacob Peattie Commented Apr 20, 2020 at 5:27