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

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!

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.

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!

Make Relative URLs with home_url()

Standard

Let me start this one by explaining how I discovered its use. I was building a theme for a customer for use on their existing WP site, and they wanted a custom menu designed that pointed to specific pages, meaning the links had to be hard-coded into the theme.

(I know… this isn’t optimal, but it was actually more efficient to do it this way than to design custom widget areas in this case. You can see the mega menu in action here, at Frederick Boulevard.)

Regardless, I found a neat trick with home_url(). Normally people use it to simply point to the home URL of a site, so it is used like this:

<a href="<?php echo home_url(/); ?>">

When used in this manner, it will point to the base URL of the site using the theme, which, for instance will return

<a href="http://frederickboulevard.com">

Now, if you want to point to a specific page on the site from your theme, pass the page’s path as an argument in the function. It will look something like this:

<a href="<?php echo home_url(/i-am-new/); ?>">I Am New</a>

Which will output

<a href="http://frederickboulevard.com/i-am-new/">I Am New</a>

Using is_main_query()

Standard

is_main_query() is a new function as of ver 3.3 that allows us to target the main loop on the page, which is useful if there are several custom loops running on a page.

One basic example of its usage is for adding on to the_content filter, appending something before or after content, such as a like button or some custom text. is_main_query() ensures your addition only appears in the main query, as opposed to on each query running on the page.

Pippin Williamson does a great job of explaining its usage. I’ll leave it to him.