Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bullet proof way to avoid jquery conflicts on wordpress plugins

I have been developing wordpress plugins for a while now and i always seem to get the following issues with all my plugins Jquery conflicts issues.

I have tried so many different ways to avoid these but i always get users contacting me saying when they have installed one off my plugins it has stopped another plugin from working aahhhhh.

I really want to get this sorted because i understand how frustrating this can be for people.

I always set and option or include wordpresses jquery, below is just an example not working code.

add_action( 'init', array( $this, 'include_jquery' ) );

function include_jquery(){

                   wp_deregister_script('jquery');
                   wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"), false, '1.7.1');
                   wp_enqueue_script('jquery');

            }

Ok so after issues with this i now have a select option in the plugin admin to toggle yes or no to include jquery or not i know it is automatically installed but some users remove this, this works for some people but not all.

if you include the wordpress jquery i know you have to run your jquery with the following.

jQuery(document).ready(function ($) {

jQuery instead of the dollar sign $

i understand and have used jquery no conflict and tried and tested some if not all off these http://api.jquery.com/jQuery.noConflict/

$.noConflict();
  jQuery(document).ready(function($) {
    // Code that uses jQuery's $ can follow here.
  });

This as with the others works for some but not all users with conflicts arising still with certain users.

I am hoping that from this post some of us wordpress plugin developers could help out and post a bullet proof way to use wordpress and jquery within our plugins without getting conflict issues.

Thanks

like image 672
user1503606 Avatar asked Sep 10 '12 08:09

user1503606


2 Answers

Doesn't it work with a closure?

(function($){
    // your plugin code
})(jQuery);
like image 122
aaaaaa Avatar answered Oct 19 '22 18:10

aaaaaa


Read these parts of the codex :

  • Load a default WordPress script from a non-default location

  • jQuery noConflict wrappers

You should use wp_enqueue_scripts hook instead of init.

And you should use jQuery.noConflict(); instead of $.noConflict();.

like image 1
soju Avatar answered Oct 19 '22 18:10

soju