New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Using jQuery and AJAX for posts and pages

From: WordPress: Creating Custom Widgets and Plugins with PHP

Video: Using jQuery and AJAX for posts and pages

With the advent of AJAX--Asynchronous JavaScript and XML--and the numerous JavaScript libraries that are out there, like JQuery, that make it easy to use, web sites are quickly losing that slow request and response mechanism, and becoming more interactive and faster. WordPress utilizes these technologies. So as WordPress developers, we can use this in our client-side software. I'm going to take a look at our posts widget that we had. What I want to do is add some preview possibilities, so that when the user mouses over one of the items, they'll then be able to see a preview of what's in that particular post.

Using jQuery and AJAX for posts and pages

With the advent of AJAX--Asynchronous JavaScript and XML--and the numerous JavaScript libraries that are out there, like JQuery, that make it easy to use, web sites are quickly losing that slow request and response mechanism, and becoming more interactive and faster. WordPress utilizes these technologies. So as WordPress developers, we can use this in our client-side software. I'm going to take a look at our posts widget that we had. What I want to do is add some preview possibilities, so that when the user mouses over one of the items, they'll then be able to see a preview of what's in that particular post.

There are a couple of steps to making AJAX work on the front-end of WordPress databases. The first step is we need to write a function. This function is going to be registered with the AJAX handler. So what this function should do is it should essentially get some post data, and then it should output something that can be used by the JQuery request. So we're going to write a function tpp_ posts_comments_return, and in here, we're going to set the variable post_id.

This is going to store the ID. First, we're going to look to see if the post has a value called post_id. So if this is set, then we can go ahead and set it equal to that value. Make sure to wrap that in quotation. If it's not set, then we'll set it to zero. Since our ID starts at one, we'll know if it's set to zero, that it's not a valid post_id. So then we can say if $post_id is greater than zero, then let's go ahead and get the post and return some information.

So I'm going to create a variable called post and set it equal to the result of calling this get_post function. The get_post function takes a post_id and will return in the post data for the ID that matches. I then want to write out some HTML, and it's going to be pretty straightforward. I'm going to give it an ID of post, a div tag, and then I'm just going to output the actual content of that post. The way I do that is I just echo, and then I use my post variable, and I output a property inside of it called post_content.

If you look up the get_post function in the Codex, you'll find the definition for all of this. So let's go ahead and open our PHP up again and make sure, after this if statement, to call the die method. This is going to stop processing of the PHP and make sure that the only thing that gets returned when they call this action is our HTML. So once that function is set up, you then need to register it with the AJAX engine. So we use an action for that. The name of the action is wp_ajax_nopriv, which stands for no privileges, which allows you to access the same AJAX script that we accessed from the back end, only it opens it up, so that things on the front end of the web site can access it as well.

Then we're going to give it an action name. We're going to call it tpp_comments. The action is then going to call the function that we just wrote. So once that's all set up, we're going to need to go in, and we're going to need to create a JavaScript file. If you look here, you can see I've moved the top post into its own folder, because I'm going to create a new file. So it's better for organization. If you already had a top post PHP in the root of the plugins, make sure that you deactivate it before you create this new directory and move it in, or it will automatically become deactivated.

You're going to need to reactivate a new one once it's in this folder. Go ahead and right-click on that folder then and go to New > File. We're going to create a JavaScript file called top_posts.js. Now before we write this script, we need to make sure to set up our client here with some identifying information. The reason is with JQuery we have to access specific items, and in order to do that they have to be in classes or have IDs to them.

So we're going to go ahead and say the class for this is div is tpp_posts. We're going to set an ID for our href, and we're going to set it equal to echo the_id. It's a template tag that's for outputting the ID of the current post. We're also going to assign a class for this a. We're going to call it comment_link. So those are all defined.

Now we can go in and write our JQuery call. This may look a little strange if you've never worked with JQuery before; it takes a little getting used to. If you've gone through our other unit on working with JQuery in the admin, it may be a bit helpful. So basically what we're going to do is we're going to set up an event handler. As soon as JQuery is ready, we're going to call a function. We're passing the Dollar sign, so that we can access the shorthand notation that we use for JavaScript.

So what I want to do first is I'm going to set a mouseover event for every div in the class of tpp_posts. So I specify div.tpp_posts. That will get those. Then we can set mouseover, and then this function will execute, and that occurs. So the first thing I'm going to do is I'm going to create a variable called div, and just set it equal to the div who's firing the mouseover event.

Then I'm going to call a post. So I'm going to use a Dollar sign to refer to JQuery, and call post, and then I'm going to go to wp-admin/admin- ajax.php, which is that one file. Now there are other ways to do this dynamically, but for the sake of simplicity, I'm just going to do this right here. Another thing to note about writing this JavaScript is that it's very browser-dependent. So we've tested this with the latest version of Firefox, 3.6.8. You want to make sure that you're using that, or you may have issues with it.

Action is going to be tpp_comments. So what I'm doing now is I'm setting up variables that I want to pass in my AJAX request. The action is going to match whatever I registered after the nopriv. Then I'm going to pass the post_id. I'm going to get this from current div, and I'm going to look inside of this current object for every a object, which there will be one in each one, and I'm going to grab the id attribute.

If you remember, in that a, I set the ID equal to the ID of the post, so that's going to return my post_id. So that's the end of my post object, the data that I want to pass. Now I need to specify what I want to happen when the result comes back. So I'm going to create a function that takes an argument data, which will be the result data, and what I'm going to do is say div, which is my div tag, .append, and then I'm just going to append my data.

So I can now close that entirely. Now I've created my post. I want to make sure to return false for that function, and then I'm going to close this entire section. I'm going to add one other event for div.tpp_posts, those same div tags. I'm going to add a mouseout event.

What this is going to do is this is essentially just going to erase the data once it's been displayed. So we can just say #post, so that's going to refer to everything with the post_id, and if you look at what gets returned, they all have an ID of post. So whichever has id of post, I'm going to go ahead and remove it. Again, there are always multiple ways to do these sorts of things. I'm just trying to give you a simple idea of how to do this. So let's go ahead and save it. Take a quick glance to make sure that everything is there.

I noticed seeing it that I didn't put my ID in the attribute, but everything else-- oh, this should also be a Dollar sign. I think everything else looks pretty good. So let's go ahead and go back into our client page. Let's now set up our scripts. So if you remember from the AJAX on the administrative side, you need to create a function that's going to call the wp_enqueue_script method. This essentially embeds scripts into our file.

So we're going to call get_scripts, so this is our function. I'm going to call enqueue_script, call this one tpp_posts, and then we have this sort of strange, long string here. Basically, what we're going to do is point out our current JavaScript using path_join and using the WP_PLUGIN_URL, the basename function, the directory name function, and the current file. And then we're going to specify that we want to look into top_posts.js, right, which is our JavaScript.

So this is just a dynamic way of appending our JavaScript information, and then we also want to specify that we want to get a JQuery library. So that's all set. So the last thing we do is we add an action for the wp_print_scripts, and this is what gets executed when we load scripts into the front side.

So we'll say tpp_posts_get_scripts, which is the function we just wrote. So that will just make sure that our script gets loaded up every time our page loads on the front end. So now let's go ahead and refresh this page. When I mouse over one of these, I should now see the post underneath it, but it doesn't seem to appear. If I look down in my firebug, I can see that it has gone out and made a request, and it looks like everything is set up appropriately, only it's getting a zero back.

This might be because I'm currently also logged in as admin, and it's trying to do some kind of no privilege. So let's go ahead and log out, so that we look more like an anonymous user. Now let's try mousing over again. You can see it does appear. So when I mouse over, I get the post, and when I mouse out, it goes away, and same with this one. So as you can see, AJAX and JQuery work together to make a really fast and interactive site, and you can use it with the loop data--or with any data really inside of WordPress environment.

All you need to do is set up a function that's going to return some data, and you're going to use that admin AJAX PHP, just like we did in the admin. Make sure to register that function then as an action, and then go ahead and write your JQuery and register that script using the wp_enqueue scripts. All in all, AJAX and JQuery can make for a really interactive WordPress web site.

Show transcript

This video is part of

Image for WordPress: Creating Custom Widgets and Plugins with PHP
 
Expand all | Collapse all
  1. 1m 49s
    1. Welcome
      1m 16s
    2. Using the exercise files
      33s
  2. 23m 29s
    1. WordPress overview
      2m 32s
    2. Installing WPI for Windows
      3m 42s
    3. Installing MAMP for the Mac
      3m 25s
    4. Installing and configuring WordPress
      5m 51s
    5. Comparing WordPress 3.0 with previous versions
      2m 57s
    6. Setting up a PHP/WordPress development environment
      5m 2s
  3. 14m 47s
    1. Exploring WordPress plugins
      3m 42s
    2. Administering plugins from the WordPress admin
      5m 23s
    3. Exploring where plugins reside
      2m 51s
    4. Introduction to hooks
      2m 51s
  4. 39m 28s
    1. Creating the plugin PHP file(s)
      3m 12s
    2. More on hooks: Actions and filters
      3m 15s
    3. Installation and activation
      4m 6s
    4. Writing activation code
      3m 45s
    5. Writing an action
      5m 12s
    6. Writing a filter
      4m 15s
    7. About pluggable functions
      2m 1s
    8. Writing a pluggable function
      5m 30s
    9. Using template tags
      2m 46s
    10. Introducing shortcode
      5m 26s
  5. 26m 2s
    1. Widgets and the WordPress Widgets SubPanel
      2m 54s
    2. Comparing widgets and plugins
      1m 8s
    3. Using and customizing built-in widgets
      3m 18s
    4. Creating a new widget
      7m 21s
    5. Writing the constructor and registering widgets
      5m 20s
    6. Enabling configuration of widgets
      6m 1s
  6. 44m 59s
    1. Creating an admin interface
      5m 25s
    2. Saving data to the database
      5m 39s
    3. Securing form submission with nonces
      2m 25s
    4. Options editing post-WordPress 2.7
      4m 8s
    5. Integrating with the WordPress admin menus
      3m 34s
    6. WordPress admin dashboard API
      4m 5s
    7. Using existing options and option editing pages in WordPress
      5m 19s
    8. Using jQuery and AJAX for administration
      14m 24s
  7. 27m 13s
    1. Accessing the WordPress database
      5m 45s
    2. Using the built-in schema
      2m 21s
    3. Accessing data using $wpdb
      5m 15s
    4. Creating new tables
      7m 18s
    5. Inserting data
      6m 34s
  8. 26m 27s
    1. Introducing the Loop
      6m 22s
    2. Using WP_Query()
      3m 11s
    3. Custom filtering and sticky posts
      4m 58s
    4. Using jQuery and AJAX for posts and pages
      11m 56s
  9. 12m 9s
    1. Registering and promoting plugins
      2m 28s
    2. Creating an uninstall function
      5m 53s
    3. Backward compatibility issues
      3m 48s
  10. 15m 3s
    1. Understanding security issues
      11m 20s
    2. Internationalizing your plugin
      3m 43s
  11. 18s
    1. Goodbye
      18s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold

Are you sure you want to delete this note?

No

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.