This happens because your theme loaded the jquery library after running your code: To add a script to wordpress you need to use the add_action('wp_enqueue_scripts' , 'function_name')
function.
The example below shows how to do this using only vanilla.js (javascript). If you need to use jquery you will have to register the library with the wp_enqueue_script()
function.
Please note that I am running the script only on pages and posts:
is_single() && is_page()
.
You can take this snippet but your script will run on all the routes of the site.
Add this to functions.php
of theme:
Only with vanila.js:
if (! function_exists('mudar_span')){
/**
* Muda o conteúdo da tag span com a classe .label-new
*/
function mudar_span(){
if (is_single() && is_page()) {
?>
<script>
function ready (fn) {
if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading")
{
return fn();
}
else{
return document.addEventListener('DOMContentLoaded', fn);
}
}
ready(function () {
el = document.querySelectorAll('.label-new span');
for (let n = 0; n < el.length; n++) {
el[n].innerHTML = 'Novo !';
}
})
</script>
<?php
}
}
}
add_action('wp_enqueue_scripts' , 'mudar_span' );
In order to use jquery you need to make sure it's being included in the header:
Using jquery:
wp_enqueue_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', array('jquery'), '', false);
The last attribute false
determines the loading of script
on head
of the site. If it is true
the script
is loaded in footer
.
You can now register the script:
if (! function_exists('mudar_span_jquery')){
/**
* Muda o conteúdo da tag span com a classe .label-new
*/
function mudar_span_jquery(){
if (is_single() && is_page()) {
?>
<script>
$(document).ready(function(){
$(".label-new").html("Novo!");
});
</script>
<?php
}
}
}
add_action('wp_enqueue_scripts' , 'mudar_span_jquery' );