Screen Shot 2014-08-11 at 9.30.46 AM

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!

3194123638_33d9ffe462_b

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.

Screen Shot 2014-08-11 at 9.30.46 AM

How to add Google fonts to WordPress themes

When enqueuing Google fonts, there are five things to consider:

  1. Is the font enqueued instead of included directly in the template files or CSS?
  2. Is the font enqueued on the correct hook?
  3. Is the font URL protocol independent?
  4. Can translators deactivate the font if their language’s character set isn’t supported?
  5. Can the font be dequeued by child themes?

In this post, we’ll go over the best practices for enqueuing Google fonts in your WordPress theme. Continue reading

Sass in underscores

Sass comes to _s

I’m pleased to announce that you can now get Sass rolled into _s by simply checking the box on Underscores.me. The community has driven this change through pull requests and forks.

It’s taken a little while, but we wanted to do it right. As with the rest of Underscores, we wanted to keep it as simple as possible, offering any extra scripting with a checkbox option rather than imposing it on all developers. Not everyone compiles or uses Sass the same, so _s shouldn’t force anyone to follow one path or another. In this sense, the Sass provided takes a pure approach, not requiring Compass or any other scripts.

Worth noting along with this addition is that the Github version of _s is now purely for development. We strongly recommend only using Underscores.me to download _s, going forward.

Just like with _s itself, the Sass it uses will probably change and evolve with time. What is in place now is a structure, a starting point. Any issues, or requests can be posted on Github, and you can even roll your own using a fork. Just like _s is your theme’s starting point, you can take the Sass in any direction you want.

I hope you are excited as I am to see Sass in _s! I’d like to thank the following people – without them this would not have been possible. As this was a Github project, here are their Github usernames: @gregrickaby @bradp @hugobaeta @obenland @sabreuse @MichaelArestad @jacklenox and myself. I look forward to seeing what things people build and where they take Sass in _s.

Swag

HTML5 Galleries in WordPress 3.9

With the new release of WordPress will come the ability to declare support for HTML5 markup in galleries. Once a theme declared support, the definition list elements will be replaced by <figure> and <figcaption> for better semantics.

If you decide to not only adopt this new feature but also maintain backwards compatibility, then there are two ways to achieve that:

  1. Style not only the new HTML5 elements, but also add CSS selectors for the traditional definition list elements. This is the route we chose for _s to keep it as simple as possible.
  2. Filter the shortcode attributes and override the tag parameters. Since the shortcode_atts_gallery filter was introduced in 3.6, you’ll be backwards compatible with the latest two versions.

Continue reading

cain

Using Custom Headers for Avatars

Some themes like to use the admin account’s avatar, if available, in the header of the theme to highlight the author. However, it’s nice to be able to change that image if the admin email’s avatar is not appropriate nor changeable.

The free Automattic theme Writr, by our very own Thomas Guillot, takes the approach of using Custom Headers for customizing the avatar image. In short, we’ll be using Custom Headers to output our image, and its default image argument will allow us to insert the avatar when no custom header image has been uploaded. Let’s get started!

In header.php, we output our Custom Header image as usual.

<!--?php 	$header_image = get_header_image(); 	if ( ! empty( $header_image ) ) : ?-->
	<a class="site-logo" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
		<img class="no-grav header-image" alt="" src="<?php header_image(); ?>" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" />
	</a>
<!--?php endif; ?-->

While declaring support for Custom Headers, we set the default-image argument to be a function (which we’ll use for our avatar logic).

function writr_custom_header_setup() {
	add_theme_support( 'custom-header', apply_filters( 'writr_custom_header_args', array(
		'default-image'          => writr_get_default_header_image(),
		...
	) ) );
}
add_action( 'after_setup_theme', 'writr_custom_header_setup' );

Finally, our writr_get_default_header_image function fetches an image from the Gravatar service. If there’s no account matching the admin email sent, we can request another image to be returned from Gravatar; we’ll try to match it to the “Default Avatar” value in Settings → Discussion (that’s all that $default business). More detail on the arguments being sent can be found in the Gravatar Image Requests documentation.

function writr_get_default_header_image() {

	// Get default from Discussion Settings.
	$default = get_option( 'avatar_default', 'mystery' ); // Mystery man default
	if ( 'mystery' == $default )
		$default = 'mm';
	elseif ( 'gravatar_default' == $default )
		$default = '';

	$protocol = ( is_ssl() ) ? 'https://secure.' : 'http://';
	$url = sprintf( '%1$sgravatar.com/avatar/%2$s/', $protocol, md5( get_option( 'admin_email' ) ) );
	$url = add_query_arg( array(
		's' => 120,
		'd' => urlencode( $default ),
	), $url );

	return esc_url_raw( $url );
} // writr_get_default_header_image

That’s it; we automatically get the avatar of the admin email (or an appropriate substitute) from Gravatar, or we can simply upload a new custom header image to override it. Have fun!