Going Above and Beyond The WordPress Coding Standards

Recently, fellow tweep @Krogsgard asked about some of the things that I do to go above and beyond the basic set of WordPress Coding Standards.

To be clear, I think that the Coding Standards are the foundation on which you need to be building your coding style. They’re the foundation of writing professional-grade code for WordPress, so start with that and build on top of it.

Everything else is just bonus.

So, with that said, here’s what I try to do to go above and beyond the WordPress Coding Standards.

Note that these are things that I do – I’m not necessarily recommending them, but I wouldn’t do them if I didn’t think they improved the overall development for myself for some of the guys I work with, or for some of the people forking my work.

My WordPress Coding Standards

Braces

When it comes to braces, I follow two rules:

  1. Use curly braces (rather than colons and endif or endwhile)
  2. Comment the close comment with // end if or// end while
if( 'featured' == strtolower( $column_name ) ) {
	$label = ucfirst( get_user_meta( $user_id, 'featured', true ) );
} // end if

I always use braces, too. Even if the conditional or the loop is a single line (like above). I do this because:

  1. Most modern IDE’s can match opening and closing braces so I like to see those highlighted. They aren’t match colons and end statements
  2. When dealing with nested loops, conditions, or more complex functions, I like to know what the brace is closing if the opening brace is out of the viewport.

Generally speaking, if something opens with a brace, I will comment the closing brace. This goes for classes, functions, loops, conditions, try/catches, switch/case, and any other type of block.

I also do this in the context of markup (which you’ll see later) and in closing braces for blocks of LESS.

Function Prefixes

I prefix every single one of my functions with the name of the theme, plugin, or application (or the abbreviation thereof) unless they are part of a class. I don’t bother doing this when working with classes because:

  1. The functions are scoped within the context of the class
  2. The class provides the readability the needed when dealing with those methods

Though this is technically part of the WordPress Coding Standards, I’ve seen other developers not do this, and it can cause major conflicts with other plugins, themes, and even PHP.

Project Organization

WordPress Coding Standards - File Organization

Almost all of my current work follows the following directory structure:

  • project-root
    • js
      • dev
      • lib
    • css
      • less
      • lib
    • img
    • templates
    • lib

I use CodeKit to manage my CSS and JavaScript files, so I maintain a dev directory for JavaScript which is the unminified JavaScript, and I maintain a less directory for CSS because I write my CSS using LESS.

I also maintain lib directories in the JavaScript directories, CSS directories, and the project root. Generally speaking, those directories are meant to contain third-party libraries that I didn’t write, but are written in that specific language.

So, for example, a PHP-based library would reside in the lib directory in the project root whereas a grid system would live in css/lib.

Table of Contents

WordPress Coding Standards - Table of Contents

functions.php has the potential to become very long. As part of trying to write clean code, I try to group all of my similar functions together. We also follow this convention at 8BIT, which you can see in the shot above.

This is done primarily for two reasons:

  1. It gives a heads up as to what the file contains and how it’s organized
  2. It makes it easy to find (using CMD+F / CTRL+F) the specific area of code you’re trying to find because you can search by the groups name rather than trying to find a function.

Custom Helper Functions

Depending on the nature of the project, I occasionally have to write functions that mimic WordPress’ native functionality.

For example, in one project I needed a function like selected but it needed to work with multi-select elements, so I prefixed the function with the project abbreviation and had it perform the exact same functionality. The logic was the only thing that differed.

function gm_selected( $key, $target ) {
	// Snipped for readability
} // end gm_selected

This means that I’m able to write my markup like this:

<select id="children" name="children[]" multiple="multiple" data-customforms="disabled">
	<option <?php gm_selected( 'pregnant', gm_get_user( 'children' ) ); ?> value="pregnant">I'm pregnant</option>
	<option <?php gm_selected( '12-months', gm_get_user( 'children' ) ); ?> value="12-months">Under 12 months</option>
	<option <?php gm_selected( '1-2', gm_get_user( 'children' ) ); ?> value="1-2">1 - 2 Years</option>
</select><!-- /#children -->

Which looks almost exactly like the standard WordPress convention.

PHPDoc

I’m big on code comments (which is another post for another time), but I’ve begun the process of PHPDoc’ing every function I write. My ultimate goal is to be able to ship a docs directory with all of my work that includes well-formatted documentation for the API.

/**
 * Attempts to locate page by the specified title and then return its ID.
 *
 * @param	$title	The title of the page for which to retrieve the ID
 * @return		    The ID of the page
 * @since		      1.0
 */

If nothing else, these function comments can help explain to other developers exactly what I’m intending for the code to do even if the code isn’t clear enough.

For what it’s worth and although the jury is still out on which PHPDoc utility I’ll end up using, I’m heavily eyeing phpDocumentor 2.

Register and Enqueueing JavaScript

Though it’s perfectly acceptable to register and enqueue your JavaScript in a single line of code:

wp_enqueue_script( 'foundation-js', get_template_directory_uri() . '/js/foundation.min.js' );

I prefer to both register and enqueue the scripts:

wp_register_script( 'jquery-ui', 'http://code.jquery.com/ui/1.8.24/jquery-ui.js', array( 'foundation-js' ) );
wp_enqueue_script( 'jquery-ui' );

I prefer the more verbose method because it allows me to register a script with WordPress that I can enqueue later. For anyone that has worked with a variety of dependencies in a single project, you’ll understand this.

Basically, I like to have all of my dependencies registered with WordPress, but then enqueue them only when needed – say, for a specific page template or type of page, such as an archive – and I believe that doing it this way can help lead to more readable and manageable code.

JSLint

I prefer JSLint to JSHint despite the fact that they are roughly the same. Generally speaking, you can think of JSLint has being designed, maintained, and enforced by Douglas Crocked whereas JSHint is a fork of JSLint and community-driven, maintained, and actually a bit more relaxed than JSLint.

Though this is purely subjective, I’m a big fan of Douglas Crockford despite some of the various comments we’ve seen on GitHub, and the fact that others are against one person setting the coding conventions for a language.

His book – JavaScript: The Good Parts – helped define the way I write JavaScript. I consider it the K&R or the JavaScript language, and until WordPress defines it’s own coding conventions for JavaScript, I’d personally rather be using conventions defined by arguably the world’s leading evangelist on the language.

Markdown Over Text

When it comes to writing README files, documentation, or any thing that users need to read, I prefer markdown to text. I think it’s more readable, easy on the eyes, and can be made significantly more attractive using pre-processors for applying CSS to it – just look at GitHub or the WordPress plugin repository.

I’m such a big than that I even write my email in Markdown (and I use Mou as my Markdown editor of choice).

Is that all?

There’s always more than can be done and there are likely things that I’ve not covered here, but I can always write a follow-up post, right? Some of these things will likely change as WordPress, third-party libraries, or my own experience changes.

But as always, I’m curious about some of the things you guys do (or don’t do) as I’m always looking to continually improve my process.

26 Comments

awesome, this touches on a lot of points I’m presenting on WordCamp Philly this year. Great post.

To take your directory structure one step further, I nest a ui directory in my img directory. In the UI directory, all the elements I call with CSS appear, whereas the assets in the parent img directory are images I’m call with an <img /> tag in the HTML.

    I’ve been toying around with nesting img (and other file types) into an assets directory like you’re describing with UI.

    I think it keeps the root nice and clean, but you have to make sure you’re logical; otherwise, writing the code to access files in those paths has the potential to get messy. I’m still working out how I like.

    Also, if you end up sharing your slides or notes from your presentation, let me know – would love to take a look at ‘em!

Just wanted to share the PHP code formatting practices that I use are derived from “PHP: The Right Way”, and it is a useful and well-thought out guide for writing readable PHP code: http://www.phptherightway.com/pages/The-Basics.html

    Definitely bookmarking this one – I may end up reblogging this as a future resource post (and I’ll be sure to give you credit for the info).

    Thanks for sharing the link – exactly the kind of stuff I was hoping people would chime in with :).

Does your project folder structure imply that you will be adding LESS files to Standard at a future date? :)

Thank you for talking through your organization structure, it’s very helpful to see how more experience hands are tackling these problems! I am curious to know whether you have any standard guidelines for how you break you your front-end code—both LESS and .js files can get unwieldy at a certain size, and I’ve had a number of conversations lately about how best to modularize those files. I’d be grateful to hear your take on the problem.

    I’ll make a note of this for something to discuss. I have a method for the ways in which I handle stuff, but I’m not sold that it’s the best way – it certainly works, though ;).

    It’d be fun to hear what others think and have them chime in, too.

My ‘standards’ are still evolving, even after 3+ years of non-stop coding. I find older projects and cringe.

One thing I do is separate out my functions file. More and more, my projects (esp theme builds) have a lot of moving parts that, while perfectly OK to put in a single file, becomes a beast to maintain. I keep an admin, types, meta, and builds file, to name a few.

    Yeah – I think one of the constants in programming is that whatever you did previously is always of less quality that what you’re doing now.

    For larger applications, I’m definitely separating my functions.php file out more. In fact, I’m working on a project right now in which I have a helpers directory (ala Rails) for functions that usually live at the bottom of the functions.php.

    I also create a views directory in my plugins so that any markup is kept out of the PHP file and in its own filetype. Way easier to know where to look and makes the code much cleaner, IMHO.

Thanks Tom, that was very helpful to me. I used to keep all the dependencies in a folder named – ‘dep’.

Basically, I like to have all of my dependencies registered with WordPress, but then enqueue them only when needed – say, for a specific page template or type of page, such as an archive – and I believe that doing it this way can help lead to more readable and manageable code.

This is also a good practice for not including code that isn’t being used and reducing page-load. Not a big deal on my connection, but a bigger one on slow mobile ones, and hey a lot of Africa and Asia will be online soon.

    Exactly this.

    Technically, we should also be moving JavaScript to the footer of all pages as per Yahoo, but this is a practice that’s been suggested for years and is a mixed bag when it comes to applying it.

    But that’s a topic for another post.

      I always move whatever I can to the footer, save WordPress’ own jQuery. If you list your dependencies on register/enqueue everything should work quite nicely.

      I look forward to seeing this post. If I remember correctly, the discussion was…*passionate* at WordCamp :)

Good article! We are linking to this particularly great post on our site.
Keep up the great writing.

Trackbacks and Pingbacks

[...] Going Above and Beyond The WordPress Coding Standards – Tom McFarlin – [...]

[...] McFarlin writes his about development practices and coding standards in “Going Above and Beyond the WordPress Coding Standards“. There’s bound to be an idea or two you can use [...]

Using LESS in WordPress - Tom McFarlinOctober 16, 2012 at 8:20 am

[...] week, I shared my thoughts on Going Above and Beyond The WordPress Coding Standards. In one of the comments, K. Adam White asked how I manage my LESS files and my JavaScript [...]

[...] McFarlin put together some great tips in his recent article on Going Above and Beyond The WordPress Coding Standards. This is a list of what he does personally to make his code more efficient and readable. Even [...]

[...] McFarlin put together some great tips in his recent article on Going Above and Beyond The WordPress Coding Standards. This is a list of what he does personally to make his code more efficient and readable. Even [...]

[...] McFarlin put together some great tips in his recent article on Going Above and Beyond The WordPress Coding Standards. This is a list of what he does personally to make his code more efficient and readable. Even [...]

[...] Going above and beyond the WordPress coding standards [...]

[...] Going Above and Beyond WordPress Coding Standards [...]

[...] McFarlin put together some great tips in his recent article on Going Above and Beyond The WordPress Coding Standards. This is a list of what he does personally to make his code more efficient and readable. Even [...]

[…] Going Above and Beyond The WordPress Coding Standards […]

[…] McFarlin put together some great tips in his recent article on Going Above and beyond The WordPress Coding Standards. This is really a list of what he does personally to create his code more efficient and readable. […]

Leave a Reply

Name and email address are required. Your email address will not be published.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>