How to add Jquery to a wordpress page?

Asked

Viewed 1,539 times

1

$(document).ready(function(){
    $('.data-encerramento').each(function (){
        var $this = $(this);
        var timestamp = $this.html();

        var a = new Date( timestamp * 1000);
        var months = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];

        var year = a.getFullYear();
        var month = months[a.getMonth()];
        var date = a.getDate();

        var time = date + ' ' + month + ' ' + year;

        alert($this.html());

        $this.html(time);
    });
});

I have this code and the $error. I need to put this excerpt in a wordpress post.

I do not have access to ftp, ti staff does not release files.

I can’t edit Theme.

How to do this code in javascript only???

  • If it’s the same at the company I work for, change it $ for jQuery

2 answers

2

Encapsulate your code in a closure, this way:

(function($){
    $(document).ready(function(){
        $('.data-encerramento').each(function (){
            var $this = $(this);
            var timestamp = $this.html();

            var a = new Date( timestamp * 1000);
            var months = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];

            var year = a.getFullYear();
            var month = months[a.getMonth()];
            var date = a.getDate();

            var time = date + ' ' + month + ' ' + year;

            alert($this.html());

            $this.html(time);
        });
    });
})(jQuery);

That way the code won’t be exposed in the global scope and you guarantee that in the scope of your function $ will always be jQuery.

It is a common practice and is shown in jquery-plugin-Boilerplate.

  • It still didn’t work for me

  • So your page is not loading jQuery or has some other script changing the value of the variable window.jQuery. Or your mistake has nothing to do with $

  • Is there any way to identify this ?? I am very limited in relation to file accesses and permissions.

  • Sign in to the browser console and type: jQuery.fn.jquery. This will return you the jQuery version or give error if jQuery is not loaded. If showing the right version means my above code will work... If it didn’t work you have to see where the mistake is, because from what you posted it seems all right

1

Try to change the $ for jQuery for example jQuery(document) as suggested by @Marcelo Bonifazio. In some cases, it may be necessary to load the script as below, this can be done using a template page for example:

 wp_register_script( 'jquery', ( 'http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js' ), false, null, true );
 wp_enqueue_script( 'jquery' );

Sources:
https://codex.wordpress.org/pt-br:Function_Reference/wp_register_script
http://wpsnipp.com/index.php/functions-php/loading-jquery-from-the-google-cdn-with-wp_register_script/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.