Scheduling Events with WordPress Tutorial

Standard

There are many reasons to schedule events; maybe you need to check an external API, or prehaps periodically empty a cache. This process can even be used for something as simple as making a post un-sticky after a certain length of time.

Scheduling Events in WordPress is basically running a Cron, just simplified by WP. There are several functions available as tools for this process, and here we’re going to take a look at three of them:

In the code at the bottom of this post is a plugin that you can insert into your wp_content/plugins folder. It will produce an admin menu item entitled “Schedule Event Tutorial.” This plugin is very simple: You check a checkbox and set a time for it to become unchecked. After that time has passed, the checkbox will become unchecked.

Screen Shot 2013-11-11 at 10.23.07 PM

The Process

The way the plugin works is that when the checkbox is checked and a time is selected, a function is run that does two things:

1. Checks to see if another “unchecking” event is already scheduled. If so, it removes that event.

2. Schedules the new “unchecking” event.

How it Works

First of all, The actual unchecking is done by the function uncheck_checkbox(). You will see around line 44 that we have hooked that function into the action we’re calling ‘uncheck_event_hook’.

This is just like any other add_action(). The array(__CLASS__….) part is a part of the Object-Oriented Programming we’re using. It tells the add_action function that we’re referencing a method (funciton) inside this class.

add_action( 'uncheck_event_hook', array( __CLASS__, 'uncheck_checkbox' ) );

The interesting part is teling ‘uncheck_event_hook’ when to fire.

Now, follow along in the schedule_event() function…

First, check to make sure process only runs if the “Save Changes” button has been pressed.

if ( ! isset( $_GET['settings-updated'] ) )
    return;

Then a check is run to see if an event exists on this hook. It gets the next time this hook is scheduled to fire by using wp_next_scheduled. Then, if any value is returned, wp_unschedule_event is used to unschedule that event from the ‘uncheck_event_hook’.

// Remove any scheduled event on this hook
    $scheduled_event = wp_next_scheduled( 'uncheck_event_hook' );
    if ( $scheduled_event !== false ) {
        wp_unschedule_event( $scheduled_event, 'uncheck_event_hook' );
    }

Next, we do the actual scheduling. We grab the value of our expiration time setting, and if it’s a number, we set the time the ‘uncheck_event_hook’ will run.

// Schedule the event to uncheck the checkbox
    $exp_time = self::expiration_time();
    if ( is_numeric( $exp_time ) ) {
        wp_schedule_single_event( $exp_time, 'uncheck_event_hook' );
    }

At this point, we wait until the time passes our expiration time, then on the next time any page is viewed on your site, the ‘uncheck_event_hook’ will fire off uncheck_checkbox(), as we set in the add_action() at the beginning of the process.

The Full Plugin Code

I decided to write this as a fully-featured plugin for a few reasons:

  1. An installable plugin would help make this process a bit more practical
  2. I learn best by viewing others’ code. Maybe you can learn something new by looking at how another developer does it

By presenting the full code, less-experienced developers have the chance to learn more about Object-Oriented code, as well as what it takes to set up a Plugin. Of course, if you have any questions about what’s going on, be sure to hit me up. I’d love to help you on your way to learning something new!

Tutorial: Writing a Unit Test for WordPress

Standard

WordPress Unit Testing is an expanding field in the WP world. Currently, there is a big push to add more tests, and you can get in on the action!

If you need help getting started with Unit Testing, check out my previous post about why to get into WordPress Unit Testing. It includes a short section about how to get rolling.

The Basics

The way the test works is relatively simple: a developer makes changes to a WordPress file, then runs the tests to make sure nothing breaks because of their changes. It notifies the dev if he/she needs to change something in their code.

Think of tests as a way to prove that a function still works properly. It tests for the expected output, so sometimes writing a test isn’t very satisfying because, in theory, your test will cause no reaction because everything is working fine.

Important

Unit tests are written to ensure WordPress returns the expected output. To be clear, they are not written to specifically test one’s code, meaning you don’t usually write a test for the sole purpose of testing your new code. To put it another way, Unit Tests exist to prove WordPress works, and if you run your code against all of the WP Unit Tests, you can see if your edits affect the output that WP creates, you can see if it breaks WP’s basic functionality.

A Basic Unit Test

Unit Tests are written then submitted to WordPress Trac to be included in the repository of Unit Tests. They can be very basic or very complicated, but they always seem to do obvious things; they make sure input is processed into the expected output.

I think this can best be explained through example. The following Unit Text will almost work. For the sake of clarity, I’ve left out some of the class information, but check it out as an example to get an idea of how a test is written.

/**
 * Test to see if get_post works.
 *
 * Compares a post ID ($org_post_id) with post ID 
 * taken out of get_post ($new_post_id).
 * If they don't match, get_post() doesn't work, and it will 
 * return an error.
 */
function test_get_post() {
    //Create new post using method provided by WP
    $org_post_id = $this->factory->post->create();
 
    //get post object using the new post's ID
    $post_obj = get_post( $org_post_id );

    //Get the post ID as given to us by get_post
    $new_post_id = $post_obj->ID;

    //Use pre-defined method to test if the two ID's match
    $this->assertEquals( $org_post_id, $new_post_id );
        
}

The purpose of this test is to see if the mechanism of get_post() is broken by whatever changes you submit with your new code. This test should work fine, as long as get_post() works. If it fails, then you know you’ve done somthing to mess up get_post().

A Full-Featured Example

This is a Unit Test I’m working on for the upcoming save_post{$post_type} action hook. The hook is all ready, and this test that I have written just needs to be tested. So, it may have some errors, but it will give you the general idea of how a test works. Check out the comments in the Gist for information on how it works. To fully understand it you’ll need to have a good grasp on Object Oriented Programming (OOP).

If the font size bothers you as much as it does me, you can view the gist here.

A Note

Weston Ruter added a comment greatly simplifying this process, which would be the best way to run this test. One of its greatest benfits is that it is extremely compact, although a bit advanced for a less-experienced developer, which may be you. I’ve decided to leave “the long way” to run this test here in this post so you can view more of the features and techniques of Unit Testing.

More

I hope you were able to learn something from viewing the actual code from a Unit Test. I’ve found that always helps me much more than reading long explanations. However, if you have any questions, I’m glad to answer them. Unit Tests are a real need in WordPress, and I’d love to help the community by assisting future Test authors.

Why you need to get into WordPress Unit Testing

Standard

What is Unit Testing?

A non-technical definition of Unit Testing, is “a way to make sure your code won’t break stuff.” In the WordPress world, it means using a provided library of tests to check if your code will return errors. Basically, it’s a program that you put your code files into, and when you run it, you will be notified if there are problems.

It’s important to know that WordPress Unit Testing is typically done with PHPUnit. You’ll see that name thrown around here and there when researching this topic.

Why Automated Testing?

Holy crap, WHY NOT?

In the past, I wasted a lot of time clicking back and forth between posts and settings pages to ensure that my new plugin or theme wouldn’t throw any errors in a WordPress install. Now, you can just type a few commands and your code will be analyzed quickly and thoroughly. Automated Unit Testing lets you quickly check your code in many, many different contexts and scenarios.

Unit Testing has proven invaluable to me in my attempts to write patches for WordPress Core. One time I ran some code I thought would work, and it broke WordPress in 9 other places. Luckily I was able to test it before I submitted it for review, right?

Unit Testing can also reveal unexpected output. Recently, automated testing revealed to me something I didn’t expect to see: when typical date formats were passed into a function, it executed perfectly, but when just one other date format was sent through, it spit out data I hadn’t accounted for. I’m not sure I would have caught that error on my own. It would have required running my code by hand many times and many ways.

Typically, testing looks like this:

  1. Edit code.
  2. Switch to browser.
  3. Input data (e.g., create a new post/comment, ativate a plugin, change admin settings, etc).
  4. Cross fingers.
  5. Check 80,987,096 places for error messages.
  6. Hope you didn’t miss anything.
  7. Repeat 9,464,643,943 times, just to be sure.
  8. Spend the rest of your day answering support questions about errors caused by your last Plugin.

The automated testing process looks more like this:

  1. Edit code.
  2. Switch to terminal.
  3. Start unit testing ($ phpunit).
  4. Make a glass of ice tea.
  5. Wait for Test Results.
  6. ???
  7. Profit.

How to Test your WordPress App, Theme, Plugin, or Patch

Tom McFarlin wrote a great series on this topic, so I won’t waste time and space trying to explain it all over again (and probably in an inferior way). Check his article out on WPTuts+: The Beginner’s Guide to Unit Testing: What Is Unit Testing? Specifically, check out the section titled “Preparing the Environment.” It will help get you started.

Other Resources

Conclusion

Unit testing is very important. It is way faster and way more thorough than you are. It is powerful and will save you a lot of headaches and embarassment when your code goes live. You need to get into Unit Testing.

Your Turn

So, what has been your experience with Unit Testing? What tips do you have for those getting started? Share your thoughts in the comments!

If you’re ready to get to the meat and potatoes, check out the next post, “Tutorial: Writing a Unit Test for WordPress.”

the_title() vs the_title_attribute()

Standard

You might be doing the_title() wrong.

If you have much experience with WordPress, you’ll be familiar with the_title(). This template tag is simply used to generate the title of whatever page or post you’re working with at the current point in The Loop.

Basic Usage of the_title()

    //Inside the Loop

    //Common usage
    <h2><?php the_title() ?></h2>

    //or better yet...
    <?php the_title( '<h2>', '</h2>' ) ?>

Another Common Use of the_title()

Usually a post’s title is wrapped in a link (usually rendered by the template tag the_permalink), and it makes sense to use the post title as the link’s title attribute. So, this is what’s commonly done to generate the link’s title attribute:

    //Inside the Loop

    //Common Post Title Linkage 
    <h2><a href="<?php the_permalink(); ?>" title="<?php the_title() ?>" ><?php the_title() ?></a></h2>

    //Just for clarity, this will output the following markup
    <h2><a href="http://mywebsite.com/my-post" title="My Post">My Post</a></h2>

The Problem

The HTML Spec restricts the characters that can be used in HTML attributes (title="" is an example of an attribute). For instance, ampersands (&) are not allowed to be used in attribute values, so you can’t do something like this:

<h2><a href="#" title="Dog & Pony Show">Dog & Pony Show</a></h2>

(It’s important to note that only the first ampersand in this statement is a problem. The second one is just part of the text as far as the browser’s concerned.)

So what can you do if your post title has one of the illegal characters (less than, greater than, ampersand, double quote and single quote) in it?

The Solution

Savvy WordPress devs know to use esc_attr() when outputting a string into a HTML attribute, which is what we just did above: We output the string “Dog & Pony Show” as the value of the attribute ‘title’. esc_attr() converts illegal characters into their HTML Entities, meaning “&” would be encoded to &amp;, then rendered as the correct character by the browser.

This is where the_title_attribute() comes in.

the_title_attribute() basically does two things with your post title: it runs the title string through PHP’s stripslashes() (a common security procedure), then it gets sent through esc_attr() to encode illegal characters. The effective line in WordPress Core literally looks like this:

// From wp-includes/post-template.php
$title = esc_attr(strip_tags($title));

In the end, your post title is all cleaned up and rendered as valid HTML.

Proper Usage

<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute() ?>" ><?php the_title() ?></a></h2>

//Which will render
<h2><a href="http://my-website.com/dog-pony-show" title="Dog $amp; Pony Show" >Dog & Pony Show</a></h2>

Conclusion

the_title_attribute() is a little-known tool in the developer’s toolbox, but it sure is handy. Be sure to include it in your next Plugin/Theme files.

What other little-known helper functions do you know? Share them in the comments!

The First Step To Coding Like A Pro: Formatting

Standard

At its core, good formatting is more than putting a spit shine on your plugin or theme. Its something that is done from the moment you crack open that first blank text document and begin writing. Formatting is the practice of careful, conscious coding.

I interviewed for an awesome job last week. They were interested in me and wanted to see a code sample of my work. I didn’t have much that was ready for review (because I’ve been working in Front End Development for the last year), so I wrote a Plugin from scratch. I went 96 hours with only a couple of naps, working my hardest to crank out coding perfection. I threw in everything that I could think of: AJAX, OOP, Validation/Sanitization, Actions & Filters, the Settings API, even localization. When I was done, I proudly submitted it for review.

What was the reviewer’s response back to me? “Your code is sloppy.” In fact three-fourths of his comments related to tabs and spacing.

Why did he care so much about such small details? Once I took the time to think about it, the answer became obvious.

Why Formatting Matters

1. It makes your code better.

If your code is written to the correct standard, it has been written and reviewed with attention to detail. It takes several passes to get any file up to standard, and in the course of formatting, you’d be surprised how many bugs you can find. Reviewing your code means refining your code. To put it another way, I can’t imagine you’ll ever see beautiful code that throws lots of errors or breaks things.

Furthermore, organizing functions in a logical way helps you see new ways to write your program. It can show you places where you are repeating yourself, revealing good sections to turn into classes/methods. Don’t forget the DRY principle of programming: Don’t Repeat Yourself.

Good formatting includes commenting your code. It makes your work easy to navigate, allowing others to troubleshoot errors, as well as reminding you of whatever the heck you were doing during the late night coding binge when you wrote it. Well documented code is much easier to extend as well.

2. It makes you look better.

It requires a lot of discipline to write clean code, and it is quickly assumed that the author of organized, well-planned code is a person with an eye for detail. Adherence to coding standards demonstrates that you are well-versed in the language/platform you’re working with. Most of all, it shows that you care; if you’re going to put in the time to do excellent work, chances are you’ll do excellent work for a client or employer.

Principles of WordPress Formatting

So, what goes into good formatting? If we need to adhere to the standards, what are they?

First of all, go take a look at the WordPress Coding Standards Doc. There are four sections, one for PHP, HTML, CSS, and JavaScript. Take the time to review each document. Here are some highlights from the docs:

PHP Highlights

  • Indent your code, and use Tabs instead of Spaces
  • Include commas after the last items in arrays
  • No shorthand PHP tags
  • Read up on the section “Space Usage
  • Commenting/Documenting code. There’s a lot here about the PHPdoc format of commenting, the industry standard.

HTML in a Nutshell

CSS Notes

  • Each Selector should be on its own line
  • Use lowercase, hyphenated selectors (not camelCase or underscored)
  • Always end in semicolons (C’mon, folks, is it necessary to say this?)
  • Order Properties alphabetically

JavaScript Formatting

  • “Always put spaces on both sides of the opening and closing parenthesis of if, else if, for, forin, do, while, and switch blocks.”
  • Name functions and variables using camelCase, not underscores.
  • Use the var keyword as much as possible to keep variables out of the global scope
  • Never end an Object with a comma
  • jQuery and that pesky $

Best Practices

Some of these rules will be natural for you based on your background, but for those which aren’t, keep a list of important formatting points handy. Practice these standards in everything you write, no matter how seemingly insignificant, and they’ll become part of your personal style of coding.

Unless you’re still using NotePad, your IDE (text editor) should have some good tools to help you format your code correctly. Turn on syntax highlighting based on the language you’re using, and set your preferences to eliminate trailing spaces on save.

One of the best ways to clean up your code is to have it reviewed by others. Find some other WordPress geeks and review each other’s code. Be teachable. The process will be humbling, but it will grow you as a developer.

Conclusion

In the end, I got the job! When all was said and done, the reviewer was able to see past my amateur-ish-ness and see potential in my work. Good leaders acknowledge that this is a learning process for us all (In fact, in writing this post I’ve noticed a few things I need to go back and fix in my own code).

So what questions do you have about WordPress formatting? Do you have a horror story about ugly code? Leave a note in the comments!

Send Emails through WordPress with wp_mail

Standard

This handy function allows you to tell WP to send email. I’m using it to send emails requesting feedback on a customer service site. Its implementation is surprisingly simple.

<?php wp_mail( $to, $subject, $message, $headers, $attachments ); ?>

I created an action that hooked into save_post, and when the post (a support ticket) is updated to “closed” (a custom taxonomy), an email will be sent. It’s amazingly easy.

wp_mail from the WordPress Codex.