WordPress: Creating Custom Widgets and Plugins with PHP
Illustration by John Hersey

WordPress: Creating Custom Widgets and Plugins with PHP

with Drew Falkman

Video: Using jQuery and AJAX for administration

WordPress developers are increasingly looking to use AJAX. AJAX stands for Asynchronous JavaScript and XML. It's a term that essentially defines the methodology of having JavaScript make calls to services to get data, and that way you can update the user interface without having to go to the server and regenerate an entire new HTML page. Overall this makes for a faster and better user experience. Fortunately, WordPress has his built-in, so we can use AJAX calls directly, and it also has a number of libraries, like JQuery.
Expand all | Collapse all
  1. 1m 49s
    1. Welcome
      1m 16s
    2. Using the exercise files
  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

Start your free trial now, and begin learning software, business and creative skills—anytime, anywhere—with video instruction from recognized industry experts.

Start Your Free Trial Now
please wait ...
Watch the Online Video Course WordPress: Creating Custom Widgets and Plugins with PHP
3h 51m Intermediate Nov 04, 2010

Viewers: in countries Watching now:

In WordPress: Creating Custom Widgets and Plugins with PHP, Drew Falkman teaches PHP developers how to create custom functionality for WordPress 2.0 through 3.0 using widgets and plugins. This course starts by installing and setting up WordPress 3.0 on both Mac and Windows, then provides an in-depth look at tasks related to these WordPress add-ons: installing and administering, building and customizing, creating editable options and database tables, working with posts and pages, and utilizing jQuery and AJAX. There are also tutorials dedicated to promoting a widget or plugin, adding security, and localizing the interface. Exercise files are included with the course.

Topics include:
  • Installing WPI and MAMP server solutions
  • Administering WordPress plugins
  • Introducing hooks
  • Writing the PHP for a plugin
  • Using template tags and shortcode
  • Building a new widget
  • Creating an admin interface
  • Accessing the WordPress database
  • Using jQuery and AJAX for posts and pages
  • Registering and promoting plugins
Developer Web
Drew Falkman

Using jQuery and AJAX for administration

WordPress developers are increasingly looking to use AJAX. AJAX stands for Asynchronous JavaScript and XML. It's a term that essentially defines the methodology of having JavaScript make calls to services to get data, and that way you can update the user interface without having to go to the server and regenerate an entire new HTML page. Overall this makes for a faster and better user experience. Fortunately, WordPress has his built-in, so we can use AJAX calls directly, and it also has a number of libraries, like JQuery.

So let's look at how to put those into our admin pages. To start, WordPress has a special file called adminAJAX.php that's used for all the AJAX calls. We can write functions in our PHP that can be used by this file to return some kind of data, to do whatever it is we need to do. So we are going to use AJAX to do some e-mail validation. We are going to do some simple scripts, and truth be told, you could probably do this directly in JavaScript, but it's a good way to illustrate the power of it.

And in addition, when you call to a server like this, you can also make checks to see if an e-mail exists in the database or do a little bit more heavy crunching than you might be able to do just in JavaScript. WordPress allows us to create functions that can be called on via the admin AJAX.php file. These functions are essentially going to get data posted to them, and then they can then out put some data, XML, JSON, or some other information. So let's go ahead and write one that does can validate e-mail for us. So we will call it cccomm_e-mail_check.

And first what we are going to do is we are going to set a variable called e-mail, and what we can do is we are going to set it equal to either an e-mail that's been posted or null, depending on whether it has been posted or not. So we can do this little check, is set--it's a handy little function if you've never used it-- _post, which is where all of our post data comes to, and we'll say cccomm_cc_e-mail. So this actually matches the name of our field that we created for our settings.

So if it is set, then were going to set the variable equal to that. If you remember, we are using the shorthand 'if-else' statement. So, basically this is the check, and this is the 'if', and then we can do an 'else', and if it isn't found, then we will just set it to null. Then we are going to create the second variable called message, and in there we are going to default it to invalid-- in other words, guilty until proven innocent-- and then we can go ahead and do our check.

So will say if e-mail, and what that statement does is that will test whether it's null or not. So if it's null, then this will fail. If it's not null, then that means we have something set in there, so now we can validate it. And there's a special function built-in into WordPress called is_e-mail, which will perform the validation for us. If it is an e-mail, than we just simply set message equal to valid, and in the end, we are going to out put whatever in our message string and then die, and make sure you do this.

This essentially stops processing so that nothing else inside the M and AJAX give process. It's a good idea, because if you don't do this you might find you get a zero, or -1, or something weird at the end of your call. So that's basically it, on the server side of things. On the client side of things, there's a little bit more. We need to create a JavaScript. So let's go ahead and go to New > File, and we'll create cc_comment.js, and make sure it's in the same directory, the cc_comment directory.

This might look a little weird at first. This is jQuery syntax. It takes a little getting used to, but once you used to, it make sense. We are basically going to say, when jQuery is ready, then we are going to call this function. Now because jQuery in WordPress runs in what's called no conflict mode, you usually can't use this special dollar sign prefix, but if you pass it to this function, then you'll be able to use it throughout. So let's go ahead and pass it to this function.

Now what we are going to do is, once it's ready, we're now going to set up an event handler to handle when the user tabs out or somehow loses focus once they've gone into the e-mail input. So what we do is we use our $ sign-- it's a signifier to jQuery--and we'll specify that we want to refer to an input in our document where the name=cccomm_cc_e-mail, which not coincidentally is what our option input is called.

So this should find that input in our document, and then we are going to add a blur event handler to that. And in the blur event handler, we are going to do our AJAX call. So there's an AJAX method, and the way it works is it takes a little object inside of which you set the type, and we are going to send it POST. You can set the data that you want to send.

In this case, I'm basically going to build like a little URL string, so I am going to say cccomm_cc_e-mail is equal to, and then I am going to concatenate on this. This in this case refers to the input, because that is essentially what this method is running on. And then we are going to get the value attribute, whatever is stored in there, which should be your e-mail, correct? And then we are going to add on what the action is, cccomm_e-mail_check, to URL.

Just type in ajaxurl just like that. It's an auto magic variable that exists in there, because the WordPress environment sets it up for us. Now we are going to set a special the beforeSend. The beforeSend is what's going to happen, essentially, before we make this AJAX call. And what we are going to do is we are going to say, e-mailInfo. We are going to prefix this with a pound, which just like css that means it is going to refer to something with the ID of e-mail info.html.

Then we'll say, "Checking e-mail," and that's going to refer to a div tag. I didn't add it earlier, but we'll go in and add it in the second. So that's beforeSend, now we can do the success. So success is when our data comes back, and the handler for success can take an argument of data, which is going to be the actual data that we get back. The data we get back is going to either be the string valid or the string invalid, depending whether or not it passed.

So we can do that test here. We can say if data=valid. Then we can say, #e-mailInfo.html, "Email OK" else e-mailInfo.html, "You have entered an invalid e-mail." So that's basically it. Let's go ahead and clean that up.

Let's make sure we've got everything in order here, and see we have our if-else, we got that brace. This brace refers to our AJAX call, this one do our beforeSend, this one to the function on the blur, and then this last one to the jQuery. And we can end each of these with a semicolon, just to keep a clean. Just go ahead and save the script. Let's go back into our PHP file. Right up here where the setting field is, you can see I have added a div file, with an id of e-mailInfo.

This is where I am going to output that information. If you haven't added that, make sure to add that now. The last step then in making this all work is to include all of these scripts. So to include our AJAX call, we use the action wp_ajax_--and this is a special one, it's dynamic. So wherever you want the action to be in that AJAXadmin or adminajaxphp, you want to put it here, so we called it cccomm_e-mail_check, and then the function you want to run, which is going to be cccomm_e-mail_check.

So note that whatever comes after wpajax_ here is going to match the action that you specified here. So that sets up the server side of things. Now, we are going to add an action for including scripts, so the action is called admin_print_scripts-options-general. php, and then we are going to specify a function that we haven't created yet but we will create right now, called cccomm_e-mail_check, and you can go ahead and copy that.

So look at this action here. This is another dynamic one: admin print scripts is used to include JavaScripts. You can also specify a page. If I don't specify it, it will include on every admin page. But since I'm only using it on options general page, then I can specify only to include it there. So the last thing is to write this function to set up my scripts, and the way this function works is there's a special function called wp_enqueueu_script, and you specify the name of the script.

And then you specify where the script is. In the last unit, we just output a static icon. Well, I could have done it dynamically, and this is what it would have looked like if you want to access something dynamically. So we put path_join, and basically what we can do is we're going to get the base of the plugin path, and then we're going to add /our JavaScript. So we'll say path_join. We can use this special wp_pluginurl to specify that we are going to go into the plugin directory.

Then we will say base name, and then we will say directory name for the current file, and then right here we can append cc_comment.js, so that we will get our script. And then lastly, we can also go out and get additional libraries. So I am going to create an array, and I am going to specify in this array--actually, I'll use single quote--'jQuery'.

There are other ones available to access. If you go into The Function Reference/wp enqueue at the WordPress Codex, you can see it will not only tell you what all these mean exactly, and how to use them, but it will also tell you which specific ones are available. You can see we have these Scriptaculous ones, SWFObject for embedding SWFs, and we have a number of different jQuery libraries as well. In addition, we have all the built- in things that are used by WordPress; you can access any of these in your files.

So I have got this all set up. I think I spelled enqueue wrong, but it looks good. So let's go ahead and save it, and let's go back into the admin, and make sure our plugin is activated, cccomm, and it is, so in our settings file we should see our comment, and one really helpful thing is you see this little bug I have right here. This is the firebug plugin that you can get from Firefox. This can be really helpful if there's ever any issues, because it will tell you what requests and responses are being made.

It will give you specifics about JavaScript errors; otherwise is very hard to debug. So if I'm tabbed in here, and I tab out, I got this message here that I have three errors. This is thank you to firebug, so you can see it's giving me error. This is not defined. So let's go back and see where that's being called. I think I made a typo. See how the $ sign is inside of this? It should actually be outside of it. It comes before it. So let's go ahead and save it, and make sure you refresh the page.

I like to hold the shift key down with Firefox. It will make sure that it clears out anything that's in memory as well and loads a fresh version. So now I will go into My Comments. When I tab out, it tells me it goes to check it, and the e-mail comes back okay. And if you look in firebug, on the console, you'll see that I have a post. It will tell me what was posted, and then it will tell me what was returned, which is valid is, which is what I would expect. However, if I typed in an invalid e-mail, you can see it went out, and it returned invalid, and gave me the correct message. So, all in all, I did that without having to refresh the page, and that's the power of AJAX and jQuery.

So WordPress has integrated AJAX and jQuery into the admin, so that we can integrate this and ultimately create a smoother and better experience for our users.

Find answers to the most frequently asked questions about WordPress: Creating Custom Widgets and Plugins with PHP .

Expand all | Collapse all
please wait ...
Q: Do I need a web hosting service for this course?
A: You don't need a hosting site to do any testing or development work that’s covered in this course. However, if you want to have your WordPress site available to the public, you will most definitely need a WordPress site. If you are hosting with an independent company, they will need to have PHP and MySQL installed, and there will be some configuration differences, but basically, you can upload anything on your local version to the web site. If you are hosting with Wordpress.com, you will need to add your plugins by uploading them manually through the WP Admin Plugin screen.
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.

Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now Already a member? Log in

* Estimated file size

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.

Mark all as unwatched Cancel


You have completed WordPress: Creating Custom Widgets and Plugins with PHP.

Return to your organization's learning portal to continue training, or close this page.

Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

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.