https://wplabo.idea-hack.com/blog/code-catalog/wordpress/20681/
Two methods of correspondence when using WordPress and when JQuery does not work

Two methods of correspondence when using WordPress and when JQuery does not work

Attempting to write JQuery in WordPress does not work if it is an ordinary writing style. This is a WordPress specification, so we need to devise a way to write it.

Because it is a specification that “$” can not be used at the beginning of script

WordPress prohibits the use of “$” so as not to adversely affect other JS type libraries.

Therefore, let’s take one of the following two correspondences.

Load another JQuery

It is a method of disabling WordPress standard JQuery and loading JQuery by yourself. The method is as follows.

php
// header.php
// Described before disabling WordPress embedded version (wp_head)
wp_deregister_script('jquery'); 

//Get Jquery from Google's CDN
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>


If you do not rely on CDN, it is as follows.

php
//header.php
// Described before disabling WordPress embedded version (wp_head)
wp_deregister_script('jquery'); 

//JQuery
<script type="text/javascript" src="<?php bloginfo(template_url);?>/js/jquery.js"></script>


However, this method is not recommended.

  • Because there are many plugins that load scripts, CSS, and execute functions on condition that WordPress standard JQuery is loaded.
  • From the above, unexpected trouble (plug-in does not work) occurs

Write in a way not affected by “$”

I recommend this method. I will list it because there are several ways of doing it.

javascript
<script type="text/javascript">
jQuery(document).ready(function () {
    jQuery("h2").hide();
});
</script>
javascript
<script type="text/javascript">
var j = jQuery.noConflict();
j(document).ready(function () {
    j("h2").hide();
});
</script>
javascript
<script type="text/javascript">
(function($) {
    $(function() {
        $("h2").hide();
    });
})(jQuery);
</script>

Anything is good. I always use the last one.

If you liked this article
please click on the "Like!".

Follow on Twetter !

Related Posts