WordPress Class Based Coding: Part 1

As your WordPress projects get larger and more complicated it is important to keep your code clean and organized.  Using PHP Classes is perfect for this!  Let’s take a real-world example, in this situation we will need a custom <img /> tag because we will be doing some javascript / ajax-y stuff with it.  This requires us to add the media’s post object ID to the image tag in a data-img_id attribute.  In this example let us imagine that we will be grabbing the data-img_id attribute via javascript to pass to an ajax call which would get custom meta assigned to our image, this would then all displayed in a modal / lightbox (or whatever).

Because we don’t want to muck-up our template files with a bunch of repeated code (D.R.Y. coding) we are going to create a small function to do all the work for us which can be reused in the standard loop or a foreach.

Lets start by adding the following to your theme’s functions.php:

If you already have a constant defined for your theme path you can disregard the first line there and change the second line as needed.  Ok we are now include a file that does not exist and you theme should be white-screening or throwing an error at you.  Go ahead and create an ‘inc’ directory in the root of your theme and create a blank php file inside that directory named ‘class-2014-img.php.’  On a side note this is a pretty standard naming convention for files that will include classes, i.e. ‘class’-<your_project>-<thing_this_class_does>.php.

In our new class-2014-img.php file we’ll start by getting the basic class defined with this:

Note the upper case letters and underscores in the class name, this is also standard convention.

Ok, we now have a class that does nothing… Next we’ll define an empty function inside of the class using:

This should look familiar if you have ever written a function in PHP before with the minor difference of including the ‘public static’ before ‘function’.  This allows us to access this function outside of the class itself, like in our template files 🙂  We will be passing the post’s ID to this function which is represented by the ‘$post_id = null.’  Setting this variable to ‘null’ by default will allow up to check that we have a valid integer later as well as cause this function to not error-out should should a post ID not be passed to it for some reason.

Next we want to grab the post’s featured image ID and source with:

Should you not be using WordPress’ default feature image functionality this could easily be changed to something like:

Since we ARE using the default featured image functionality we do not need the ‘get_post_meta’ in this example.

Next we need to actually build what this function will return to our templates.  It is generally better to ‘return’ something here rather than ‘echo’-ing it here as this will give us control in the future with how we deal with what we get back from this function.  This tutorial is not really a good example of this, but trust me, just return stuff inside of you Class functions when possible:

Note the $img_src[0] here, the wp_get_attachement_src function returns an array of stuff about the image itself where ‘[0]’ is the image’s url.

This code shouldn’t be too surprising, we have an img tag, a source, and our images post ID via ‘get_post_thumbnail_id( $post_id ).’  You’ll also notice that we are escaping the source and data-img_id, while it is a little over-zealous in this case it is good practice to get in the habit.  I am considering this ‘over-zealous’ here as all the variables that we are escaping actually come from WordPress core rather than any user-entered content (which should ALWAYS be escaped), for more information on this see http://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data.

At this point your class-2014-img.php should look like:

With our Class and function in place we can now actually use what we’ve built.  In either a standard WP_Query loop or a foreach we can show the featured image with it’s ID as a data-img_id attribute using:

Depending on how you are getting your posts you may need to change $post-ID to get_the_ID().

Lastly, adding some checks to make sure all of our variables are set and what we expect them to be, our final Class should look like:

3 thoughts on “WordPress Class Based Coding: Part 1”

  1. …including the ‘public static’ before ‘function’. This allows us to access this function outside of the class itself

    .

    The difference is a little more subtle. The public keyword does allow outside access to members (variables and functions). Adding the static keyword allows you to access that function or member without instantiating the class (e.g. can use className::foo()). In fact, in PHP5.5 (may have been 5.4, I don’t remember exactly) and newer, you can only access static members in an uninstantiated manner. That is, you can’t use $this->foo() within the class, and you can’t use $classInstanceName->foo() outside of the class (where foo() is declared static). Static methods can be useful, but keep in mind that if all members of a class are static it is likely that you are just namespacing your code and are not taking advantage of other OOP principles.

Leave a Reply

Your email address will not be published. Required fields are marked *