Frontend Ajax with WordPress

Most likely if you are a theme or plugin developer you will need a way to send AJAX calls to fetch new updates or to create new database records or anything else that may require a hidden backend http call. This post will show you how that is done. Unlike the admin area, frontend ajax in WordPress is on a tricky side. We will design a really basic plugin to learn how this stuff actually works. I am using WordPress 3.6 beta. First Step We will call our plugin "Test Plugin", so lets declare plugin meta comment /wp-content/plugins/test-plugin/test-plugin.php [crayon-5997e980215ce453796758/]   Second Step Enqueue our JavaScript File ajax.js. Please note that we will be creating this file in a second. /wp-content/plugins/test-plugin/test-plugin.php (append) [crayon-5997e980215e2121876703/]   Couple of points to note above are that, First we are loading our scripts for frontend only thus we are check  if the Dashboard or the administration panel is attempting to be displayed with is_admin() function and Second we are localizing a variable called ajaxurl that we can access globally as text_plugin.ajaxurl To read more on localizing some data please read this Third Step Lets create our ajax.js file, please note that I am creating /wp-content/plugins/test-plugin/ajax.js [crayon-5997e980215e9405926652/]   As you can see that this is a really simple jQuery Ajax call. If you want to learn more on jQuery Ajax please read this. The ajaxurl javascript global does not get automatically defined for you on frontend that is why we localized this property to be available to our function in previous step. Fourth Step Ok Don't be judgemental about this one and me being lazy, but to code below should be appended to our test-plugin.php file. /wp-content/plugins/test-plugin/test-plugin.php (append) [crayon-5997e980215f0253662900/]   Few things you should know When adding actions such … [Read more...]