Utilizing ajax and other wonders within WordPress plugins couldn’t be easier thanks to jQuery. What’s more, jQuery is already installed as part of the WordPress installation (At least it is with version 2.7), so its even easier to implement! This tutorial will guide you through the steps on including the jQuery library within your plugin so that you can use all the goodness jQuery can bring, setting up your own javascript file, as well as an important tip at the end!
Including the jQuery library
Before you write any ajax code you need to include the jQuery library, so that it is loaded as part of your WordPress pages. You need to do three things:
- Create your own javascript file for your ajax code.
- Write a function that loads your javascript file and the jQuery library.
- Add an action to call the aforementioned function.
So, in your plugin directory, create a folder called “js”, and within that folder create a file called “myJavascript.js”. Now, in your main plugin PHP script, create the following function:
This function does a couple of things – 1) it points to your javascript file which you will update later, and (2) it also invokes jQuery to be loaded with it.
So now we have the function, we need to tell the plugin to call that function when the page is loaded. We do this by adding a new action, so add the following to your main PHP script of your plugin:
1.add_action('init', 'my_init');
This action will now ensure jQuery and your javascript are called in the <HEAD> part of your pages. All you now need to do is write your ajax code in your newly created “myJavascript.js” and you’re done!
VERY important note
When writing your jQuery code, you must use jQuery(”#DIV”) or jQuery.get() – emphasis on the jQuery rather than using $(”#DIV”) or $.get – Using $ will not work as its already been set aside by the javascript library “Prototype” which is also used by WordPress. It is case sensitive too, so no jquery or Jquery!!
Download
I have written the code up into a small plugin which you can view and install. Download it here. Unzip and install the folder “jQuery_WordPress_Plugin” to your “/wp-content/plugins/” directory. Full details are included in the my_plugin.php file.
Also See
Check out the tutorial on implementing custom CSS into a WordPress plugin
Hi, I used to use only
google