Prefixing in WordPress Themes

An important best practice when coding a WordPress theme or plugin is correct prefixing.

In this post, we’ll look at:

  1. Why prefixing is needed in PHP.
  2. Why prefixing is needed in WordPress specifically.
  3. How to prefix properly in your code.

Prefixing in PHP

Programming uses the concept of namespaces. It’s an abstract concept that can be explained as a type of container that contains all your code.

In PHP, all functions, classes, interfaces, constants and variables defined outside of functions and methods live by default in the global namespace.

This means that the names you give to these code constructs have to be unique.

Consider this code:

function output() {
    echo 'this';
}

function output() {
    echo 'that';
}

If you run this code (with error reporting enabled), you will get the following error:

Fatal error: Cannot redeclare output() (previously declared in /htdocs/prefixing-post.php:5) in /htdocs/prefixing-post.php:5 on line 10.

Although the functions are not identical, their names are, which creates a conflict. You could simply rename them, and you would be fine:

function output_this() {
    echo 'this';
}

function output_that() {
    echo 'that';
}

While this code runs without errors, the problem is that function names often aren’t unique. Imagine you’re writing software for blogging called Awesome Blogging. In this program you have an output() function that prints the page content.

Everything works fine until you include an external library to handle RSS feeds named Cool RSS. By chance, this code also includes a function named output() to print the RSS feed. Your program is now broken!

This is why it’s an established practice to add a prefix to all functions in a specific piece of code to avoid naming conflicts. In our example above, the first function would be named awesome_blogging_output() and the second one cool_rss_output(). No more conflicts!

You can imagine that prefixing all functions and classes and interfaces as well as constants and variables with global scope can become pretty tedious. This is why PHP introduced a namespaces feature with PHP 5.3.0, which allows you to create your own namespaces without the need for prefixing. Since WordPress currently only requires PHP 5.2.4, though, we can’t yet use this new PHP feature.

Prefixing in WordPress

Prefixing is important in WordPress plugins and themes, because WordPress Core itself does not consistently use prefixes. As of WordPress version 4.0, there are nearly 4950 functions in the Core codebase alone. Some functions and classes in WordPress Core use a wp_ or WP_ prefix, but not all of them. Since this doesn’t even take into account all existing plugins and themes, the potential for a name collision is high.

Prefixing in WordPress Themes

For themes, anything specific to the theme living in the global namespace or stored in the database should be prefixed.

This includes:

  • functions
  • classes
  • actions and filters
  • global variables
  • database entries such as options and post meta

The prefix for these elements should correspond to the theme slug, which in turn should match the theme’s lowercase name, without any spaces or special characters. For functions, classes and global variables, the underscore character should be used. For actions and filters or database entries, the dash character can be used as a separator.

For example, if your theme name is Green Hills, then all functions, classes and global variables would be prefixed with green_hills_. Hooks and database entries would use green-hills- as a prefix.

An Important Best Practice

As we’ve seen in this tutorial, name collisions can result in PHP fatal errors that break entire sites. Proper prefixing lets us avoid these disasters before they happen.

If you have any questions, feel free to leave a comment. Happy theming!

Why Bootstrap is a bad fit for WordPress Themes

Since its release in 2011, Bootstrap has quickly become the most popular front-end framework on Github. This popularity also has an impact on the world of WordPress themes, with authors using the framework during development or even releasing themes that feature Bootstrap as unique selling point.

This is surprising, because Bootstrap is not a great fit for WordPress theme development.

Bootstrap is the wrong tool for the job

Bootstrap was created at Twitter as a tool for back-end developers to easily create interfaces for their applications. Before Bootstrap, various other libraries were used, which resulted in inconsistent and difficult to maintain interfaces.

So Bootstrap was created with a precise goal in mind, and it continues to develop according to this initial vision for the project. It was created so that developers could focus on back-end code and quickly iterate without having to worry about the front-end.

This is why it’s the wrong tool for a WordPress theme: the front-end, or how the site looks with the theme activated, is all that counts.

Bootstrap does not do things the WordPress Way

WordPress facilitates theme development by providing a set of functions to be used in template files. By leveraging the HTML output of these functions, developers can write efficient and clean code that works with a variety of content.

Bootstrap on the other hand has its own approach to how the HTML is structured, and it does not fit well with what WordPress provides by default.

As such, developers have to take extra steps and write additional code to modify WordPress’ behavior to the fit how the framework works. A good example for this are navigation menus. Instead of using the output of wp_nav_menu(), developers have to write Custom Walker classes that change the HTML output by the function so that the Bootstrap CSS and Javascript can be used.

This approach results in more code and as such is less efficient, results in more maintenance and development time and also does not benefit from the enhancements made to the Core functions.

Bootstrap is bloated

Framework code can never be as efficient as code written for a specific purpose, since frameworks build up from general cases to more specific cases and add bloat in the process. Often multiple CSS classes need to be added to HTML elements to achieve a desired visual result, along with the necessary CSS.

What adds to this problem is that often times, not only the CSS code necessary for the theme’s design is packaged, but the entire framework code.

Bootstrap does not encourage great design

One of the most popular features of Bootstrap is the twelve column, fully responsive grid system. By adding classes into the HTML markup, developers can create websites that react to every screen size.

Unfortunately using a predefined grid is the wrong approach to achieving a great design. The major problem is that you are designing from the outside in, shoving content into predefined boxes. The result is designs that have a rigid and mechanical feel to them, without proper proportions or harmony.

The one-size-fits-all approach also ensures that the theme you’re designing does not adapt to any constraints like image dimensions or line length. Whether you’re using a narrow sans-serif or a didone serif that needs room to breathe, the grid stays the same. The result is often bad legibility and nonharmonic typography.

A better approach

2328591656_311f762a73_o2

Every great theme design starts with a vision. What is the purpose behind the theme you’re designing and who do you envision using it and it what context?

This will inform you about the constraints that you have to work with. Designing an image heavy portfolio theme is a different challenge than creating an optimal experience for a magazine theme featuring long form articles.

Once you have set on a vision, you then start designing from the inside out. Get some sample content for a couple of test posts and then start designing the experience of consuming that content. You’ll see that once you focus on the content first, you can build out the remaining design elements around it and achieve a harmonic result.

On the technical side, use a starter theme that provides you with enough markup to quickly start diving into the presentational markup, without being overly opinionated about the design. Use libraries and code snippets to reduce development time. The default themes that ship with WordPress are usually a good resource for extracting code snippets.

Online Resources to Help You Learn All The Things

The web industry is always changing. Just when you get settled into a routine, the flow of technological innovations force you start a new one. Can you keep up? It never hurts to set aside some time for learning new skills and sharpening your current ones.

In this post, I’ll outline a few online resources that can help you continue your education in web design and development (or to get started, if you’re just joining us).

Continue reading “Online Resources to Help You Learn All The Things”

5 Common Theme Development Mistakes and How to Avoid Them

Review is a key part of Theme Wrangling, so we spend a lot of time looking “under the hood” at themes. Here are some of most common theme development errors that come up in the review process, and some tips on how to avoid them.

Continue reading “5 Common Theme Development Mistakes and How to Avoid Them”

Theme Code Matters, Too

Hey there, WordPress theme developers. When you’re crafting themes, are you checking the quality of your theme code? The design is important, yes, but so is the code.

Hey there, WordPress theme developers. When you’re crafting themes, are you checking the quality of your theme code? The design is important, yes, but so is the code. Within the past year, the WordPress theme review team has been hard at work encouraging best coding practices among WordPress theme developers, with the goal of raising the overall standard of the themes that appear in the WordPress.org theme repository. Even if you don’t intend to submit your theme to the WordPress.org theme repository, it’s wise to develop your themes as though that was your intention. I hope that by the end of this post, you’ll have a better understanding of the benefits of doing so.

The WordPress Theme Review Team and its guidelines

Just in case this is the first time you’ve heard of the theme review team, I’ll describe it briefly. They’re a group of volunteers from the WordPress community that reviews each theme that is submitted to the WordPress.org theme repository to check for compliance with the guidelines and standards that they have set forth. I’m not going to list all of the guidelines here because you can read them at the theme review team’s website, but I do wish to highlight a few here because they’re especially relevant to coding practices:

Briefly, a description of each of the above:

The Theme Check plugin

This is a plugin that tests your theme to see if it meets the latest theme review guidelines. If your theme is missing a required or recommended feature, or if it contains deprecated functions, the plugin will let you know and suggest possible fixes.

Code quality

These are a general set of guidelines that specify how you should format the HTML, CSS, and PHP in your theme. All HTML and CSS mark-up must validate to W3C Standards, and your PHP must neither generate any notices, warnings, or errors when WP_DEBUG is turned on (turn it on by placing  define('WP_DEBUG', true) in wp-config.php).

Does your theme contain hidden PHP warnings like THIS?

The Theme Unit Test

How well does your theme handle posts without titles? Do images resize properly? Do floated elements inside posts clear properly? Are all possible HTML tags that users can use in the visual editor styled? Are all widgets styled? The theme unit test is a set of sample data that you can use to test your theme in scenarios such as these.

Example of a Unit Test post on the Twenty Eleven Theme
Example of a Unit Test post on the Twenty Eleven Theme

Of course, as I stated earlier, these are just three of the areas in the theme review guidelines. A theme passes its review and is accepted in the WordPress.org theme repository when it satisfies the criteria for all of the areas.

So, why should you care?

The theme review team’s guidelines are important for all WordPress theme developers for three basic reasons:

  1. They establish general consistency among WordPress themes for users and developers.
  2. They ensure protocols for theme security.
  3. They raise the bar for overall theme quality.

Let’s discuss these three areas in more detail.

Consistency

WordPress themes are a eclectic bunch, but they do have at least one thing in common — they are all WordPress themes. It’s important to always keep this in mind.

When your theme deviates too far from the core WordPress functionality, you run the risk of users becoming frustrated as to why certain features that they’ve come to expect from WordPress don’t seem to work with their site. Listed below are sections of the theme review guidelines that help establish a base consistency among themes in the WordPress.org theme repository:

Before you add a custom feature to your theme, check to see if WordPress already has a core function that can take care of it. The table below highlights core features your theme should utilize as much as possible.

Theme Feature WordPress Feature to Use
Custom Logo/Banner Custom Headers
Background Color/Image Custom Background
Menu Management WordPress Navigation Menus
Theme file editing WordPress Theme Editor and Plugin Editor
Theme Options Page Settings API
Theme Options Page Design Stick with the WordPress UI instead of making your own design. (Ryan Imel from WPCandy wrote a blog post on this subject)
Design options (color pickers, font size tools, border size, etc) Keep to a minimum. Encouraging users to make design changes with CSS is more scalable in the long run.
Direct Database Queries WordPress Template Tags and Functions
Thumbnails Post Thumbnails (Featured Images)

Security

Constant Vigilance: Keeping themes secure requires active, continuous effort

Themes play a large role in WordPress sites, so it pays to ensure that your theme’s code is as secure as possible. Don’t let your theme be the one that leaves your users’ sites vulnerable to hackers. No one wants (or deserves) to have their site hacked. If you follow the theme review team’s security-related guidelines, you will be one step closer to building a theme that is as safe as it is gorgeous. The following are the theme review team’s guidelines related specifically to security. I highly recommend that you read them as you develop your theme:

  • Theme Settings and Data Security – Properly escaping all data throughout your theme and using the Settings API for theme options pages are essential characteristics of a secure theme.
  • Theme Obsolescence – Outdated code and deprecated functions are a security threat because they may contain known vulnerabilities that hackers can exploit. Themes in the WordPress.org repository will be removed if they are not updated on a regular basis to comply with the latest version of WordPress. In a similar vein, third-party scripts can also pose security risks, as we saw with the recent TimThumb vulnerability. If you use third-party scripts in your theme, please, please, please check those scripts regularly to make sure they are up to date. If the original author of a script does not put out regular updates, think twice about using it. Security is never a “set it and forget it” deal — you must approach it Mad-Eye Moody-style: CONSTANT VIGILANCE.

Quality

The final reason that it’s important to pay attention to your theme’s code is for the sake of quality. A theme that uses well-formed, modern code is easier for you and other developers to maintain in the future. The larger the number of well-coded themes we have, the more positively this reflects on the WordPress community as a whole. The following area from the theme review team’s guidelines relates specifically to code quality (I linked it earlier, but I’m linking it again because it’s that important):

In addition, WordPress has adopted standards for writing PHP, HTML, and CSS. We use these standards when converting themes for use on WordPress.com:

Conclusion and … how to get started

I hope I’ve convinced you why it’s so important to pay attention to your theme’s code, whether you are creating free themes or commercial themes. If you’re interested in applying some of these principles to your theme development, here is a nice list of procedures to keep in mind during the development process:

  • Make sure you’re aware of the current theme review guidelines.
  • Look at the code of the current default theme, such as Twenty Eleven, as a starting point and as an example of best coding practices and implementing core WordPress functionality.
  • Get in the habit of testing your theme with the unit test data.
  • Turn on WP_DEBUG in wp-config.php to check for hidden errors, warnings, and notices.
  • Install the Theme Check, Log Deprecated Functions, and Debug Bar  plugins. Run their tests often to catch (and fix) potential problem areas before they pile up.
  • Before you add a custom function, check to see if there is a WordPress core function that can take care of it. If you feel that the WordPress core functionality is lacking somehow, try supplementing the core feature instead of replacing it completely. Make sure that any custom feature you add does not leave “debris” behind (such as broken shortcodes) or otherwise cause a site to break badly if users decide to switch their theme. What are your “fallback” features?
  • Consider joining the WordPress theme review team, which forces you to learn by checking others’ code. For more information, please read Justin Tadlock’s excellent post on this subject: Join the WordPress theme review team.

Resources for further reading

So You Want To Create WordPress Themes, Huh?

Update: It’s live! It’s happening! Go read How To Create a WordPress Theme and learn how to code up something awesome.


Does that title sound familiar? Over 2 years ago the now defunct WPDesigner.com published a series of posts under that banner, teaching beginners how to create WordPress Themes from scratch.

2 years ago is a long time online: Things have changed.

Starting next week, ThemeShaper will publish a series of daily lessons that will teach you how to create your very own modern WordPress Theme—from scratch—using the latest best practices.

And it won’t be just any old WordPress theme you’ll have in your hands. In a lot of ways it will surpass what’s been done with the popular Thematic Theme Framework. Except, it’ll be a little leaner, a little meaner, and it’ll be all yours.

Here’s the laundry list of features your finished theme will be able to boast of.

  • Search-engine optimization
  • Microformats
  • Localization support for translation
  • Robust dynamic body and post classes
  • Separated Comments and Trackbacks
  • Gravatar support
  • A valid, logical, semantic XHTML structure you can use to build ANY layout
  • Valid CSS
  • A strong typographical foundation
  • Smart default layouts (that we can adapt for later layout generation)
  • 2 widget areas, with NO hard-coded widgets, that “disappear” from the markup when they’re empty.
  • Styling for WordPress Image Classes
  • And pretty much all the typical WordPress stuff

When you’re done you’ll have a complete—and completely powerful—WordPress Theme that you can edit further or build on with a WordPress Child Theme. The choice is yours.

Are you ready?

We Need To Kill The Sidebar

It’s time for the WordPress sidebar to go, and all mention of it to be wiped out from existence. I’m not talking about the visual idea of a sidebar on your blog. No. I’m talking about the WordPress function get_sidebar() and the use of the term, Sidebar in the WordPress admin. This way of thinking is obscuring the vision of WordPress designers and limiting the potential of your blog theme.

Here’s why: A sidebar doesn’t have to be a sidebar. Continue reading “We Need To Kill The Sidebar”