This happens because your theme loaded the jquery library after running its code: To add a script in wordpress you need to use the function add_action('wp_enqueue_scripts' , 'function_name')
.
The example below shows how to do this using vanilla.js(javascript) only. If you need to use jquery you have to register the library with the function wp_enqueue_script()
.
Note that I am running the script only on pages and posts:
is_single() && is_page()
.
You can take this excerpt but your script will run on all routes of the site.
Add that to functions.php
of the theme:
Only with vanilla.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 is being included in the header:
Using the 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
in the head
of the website. If true
the script
is born in the footer
.
Now you can 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' );
Try it like this:
window.onload = function(){
 $(".label-new").html("Novo!");
}

– Sam