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:
function my_init() {
wp_enqueue_script( 'myJavascript',get_bloginfo('wpurl').'/wp-content/plugins/YourPluginName/js/myJavascript.js', array('jquery'));
}
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:
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
Similar Articles:
cURL on GoDaddy issue...
WordPress Plugins: Utilize CSS in 2 minutes
Cheatsheet: Wordpress plugin admin page bling!
Introducing "Twollowers" and "Twitter Search" plugins
WordPress Widget - Beginners Guide












Hello,
Ugh, I liked!
Have a nice day
Elcorin
I’ve been searching around for a good post on how to use jquery with wordpress and yours is by far the best I’ve seen.
I still have questions though.
Can I put the init function in function.php page?
Do all $ need to be changed, or can it just be wrapped in the div?
Playstation is the best gaming console that i have owned. Me and my brother are addicted in playing games on Playstation.;”.