OOP with WordPress – For the Total Newbie

Standard

Object-Oriented Programming (OOP) is a common method used to encapsulate code. Although it can be used for techniques much more advanced than we’ll discuss here, it can be used for basic plugins quite easily so you can learn its basics.

In this tutorial, we’ll create a short plugin that creates a Custom Post Type called “Books,” and an associated taxonomy called “Genres.” This is a fairly common operation in WordPress, and can certainly be created without using OOP, but since you’re probably already familiar with that process, it will serve as a good base for this tutorial.

Skip to the full code »

The primary “element” of OOP is the Class. For our purposes, it’s a wrapper that holds all of the internal functions, which in the context of OOP are called methods.

Creating a Simple Class

We start by creating our Class.

class JR3_Books {
     static function setup() {}
}
add_action( 'plugins_loaded', array( 'JR3_Books', 'setup' ) );

Our Class is “JR3_Books.” Each word in a Class’s name is capitalized, and underscores represent spaces.

Inside of it, we place a method that we’ll call setup(). You’ll note that you usually want to prefix your functions in WordPress to avoid conflicts, but since this is within our Class, it isn’t necessary.

You’ll note the word static before the method setup(). This is important for the way that we will be calling our methods in this tutorial, but the reason why isn’t important right now.

Firing the Class

Finally, we called the plugins_loaded action after the class. This is an important thing to note, as we’ll use a similar format within the Class.

Note that usually, an action looks like this:

add_action( 'plugins_loaded', 'setup' );

However, we have to let the add_action() know that setup() is located within our Class.

This is done by turning the second argument from a simple string into an array that includes the name of our Class, which gives us this:

add_action( 'plugins_loaded', array( 'JR3_Books', 'setup' ) );

Note: There are a lot of ways to instantiate a Class, and some are more appropriate than others. For the sake of simplicity and consistency in this tutorial, I’m taking the simple add_action() route

Adding A Method

Now, we add our method to register the post type. This will be done very similarly to how we commonly use register_post_type(), and we’ll use an action to fire this off in just a minute.

For now, this method goes within the Class, just like our setup() method.

static function register_books_cpt() {
     register_post_type( 'jr3_books', array(...) );
}

Note that I haven’t filled in the register_post_type() function completely here for the sake of clarity.

So, right now, our plugin doesn’t do anything. As I said above, we need to use an action to make this new method fire off. We do this by adding the appropriate action within our setup() method.

static function setup() {
     add_action( 'init', array( __CLASS__, 'register_books_cpt' ) );
}

Once again, you’ll note that we’re using an array as the second argument in the action. This time, however, we aren’t using the Class name, “JR3_Books.” Within a class, you use the Magic Constant __CLASS__. Also, the second value in the array is the name of our new method.

To translate this action into words, it tells the code to, on init, look inside of this Class for the method register_books_cpt.

In the code snippet below, you’ll see that I’ve also added a method for adding a custom Taxonomy (called, “Generes”), using the same technique.

Conclusion

What we’ve done here is we created a Class to hold our code. Inside of it, we added a setup() method to maintain the actions we’ll fire during our plugin. Then, to kick things off, we added the add_action( 'plugins_loaded' ... ) to tell WP to load our Class.

Naturally, this is a very high-level view of OOP. These can do extremely intricate and complex functions for you on your projects, and I hope that this will get you on your way to understanding how they work!

BONUS: The code below is a partial example of what we’ve covered. Here’s a fully-functional example this code that you can place in your wp-content/plugins directory to play around with.

Further Reading

 

Basic Example of this Tutorial

Please Change Your Genesis Favicon

Standard

I love the Genesis framework* for WordPress. It is an amazing tool for speeding up the development process, and I even use it on my personal site.

Its wide acceptance across the WordPress world is unfortunately highlighted by the proliferation of Genesis favicons on these sites.

The Genesis Favicon is a black square or circle with a white capital “G” in it. It is a dead giveaway that you’re running your site on Genesis.

If you’re developing custom sites for your clients, you probably don’t want that visible. Your client would probably prefer to have their own branding in their favicon.

The fix for this is pretty simple, thanks to the hooks that Genesis offers.

What is a Favicon?

A favicon is that little square icon that appears in your browser window (or tab). It’s actually not a typical image, but an .ico file type.

The black circle in this browser tab is an example of a Genesis favicon.

The black circle in this browser tab is an example of a Genesis favicon.

To create your own favicon, create a square logo image with your brand of any size larger than 16x16px (you can even use transparent .pngs). Then, go to a site like favicon-generator.org and convert it to an .ico.

Including Your Custom Favicon in a Genesis Child Theme

Typically, this file is named “favicon.ico,” but you can call it whatever you want. The name “favicon.ico” is used in my code sample, so you may have to adjust that as needed.

Add your favicon to your Genesis Child theme’s directory, and add the following code to your child theme’s functions.php.

Note: Browsers are pretty stingy about caching these favicons. This means that you’ll need to open your site in a private/incognito window to see the changes take effect. New visitors to your site won’t need to do this.

*Not an affiliate link

New WordPress Plugin: Send System Info

Standard

When providing support for WordPress do you waste time going back and forth with the client asking for information about their website? Information like versions of WordPress, PHP and MySQL, as well as configuration of each can be invaluable to diagnosing a problem quickly and accurately.

After some work with the team on the Stream Plugin, I realized the need for users to easily gather information about their site’s configuration. This idea gave birth to the Send System Info Plugin for WordPress.

This plugin not only displays the site information, it allows the user to send this data to you in three forms:

  1. A downloadable plain text document, handy for archiving for later comparison
    SSI-Top
  2. An email generated within the plugin
    SSI-Email
  3. A URL that allows secure remote viewing of this data
    SSI-Remote-Viewing

My favorite feature of this plugin is the remote viewing URL, which points to a plain text page of the site information. The cool thing is that this URL can be regenerated, wiping out access to those who have the previous URL.

This is especially handy for posting site information in support forums, where you have no contact email address with those providing support, like the WordPress.org Support Forums. This link can be posted to the forums, and when you are done getting the support you need, simply regenerate the URL and later visitors to the forum will have no access to your information. This is a much more secure method of getting help than simply writing your server information into the forum.

I’ve had some great help from Frankie Jarrett and Luke Carbis and Pippin Williamson on Send System Info. You can help out, too! I have a GitHub repo available at https://github.com/johnregan3/send-system-info, and contributions are always welcome. I want this plugin to be as useful as possible for the WordPress community.

I invite you to download Send System Info and give it a test run. I think you’ll be surprised at how much information is available, as well as it’s simplicity and how easy it is to use. Give it a shot!

Adding Support for Vertical Featured Images in WordPress Themes

Standard

Here’s a quick and easy way to add support for Vertical Featured images in your WordPress themes.

How it Works

Using a filter hook, we’re going to add a class to the Featured Image markup if the image’s height is greater than its width. Then, using CSS we’ll float it to the right. Pretty simple, huh?

The Script

In your functions.php file add:

The CSS

This code floats the image to the right and adds some margin to separate the image from the post’s content. Be sure to include it in your CSS file.

.vertical-image {
	float:right;
	margin-bottom: 1em;
	margin-left: 2%;
	max-width: 33%;
}

Caveats

Your Post title will need to be clear: none; if this happens:

Screen Shot 2014-01-02 at 2.13.46 PM

You may need to add overflow:hidden to your post’s CSS to prevent this from happening in case the post excerpt is too short:

Screen Shot 2014-01-02 at 1.59.06 PM

The Result

This is what it should look like if the Feature Image has a vertical (portrait) orientation:

Screen Shot 2014-01-02 at 1.53.14 PM

Conclusion

When researching this, I had a hard time finding resources on this topic, so I hope this helps! If you find this post helpful, be sure to pass it on, including a link to this post!

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.”