How to add Jquery to a wordpress page?

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 snippet in a wordpress post.

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

I can not edit the theme.

How would you make this code in javascript only ???

    
asked by anonymous 19.01.2017 / 17:39

2 answers

2

Encapsulate your code in a closure, like this:

(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);

This way the code will not 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 the jquery -plugin-boilerplate .

    
19.01.2017 / 18:13
1

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

 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:
link
link

    
19.01.2017 / 18:04