the_title() vs the_title_attribute()

Standard

You might be doing the_title() wrong.

If you have much experience with WordPress, you’ll be familiar with the_title(). This template tag is simply used to generate the title of whatever page or post you’re working with at the current point in The Loop.

Basic Usage of the_title()

    //Inside the Loop

    //Common usage
    <h2><?php the_title() ?></h2>

    //or better yet...
    <?php the_title( '<h2>', '</h2>' ) ?>

Another Common Use of the_title()

Usually a post’s title is wrapped in a link (usually rendered by the template tag the_permalink), and it makes sense to use the post title as the link’s title attribute. So, this is what’s commonly done to generate the link’s title attribute:

    //Inside the Loop

    //Common Post Title Linkage 
    <h2><a href="<?php the_permalink(); ?>" title="<?php the_title() ?>" ><?php the_title() ?></a></h2>

    //Just for clarity, this will output the following markup
    <h2><a href="http://mywebsite.com/my-post" title="My Post">My Post</a></h2>

The Problem

The HTML Spec restricts the characters that can be used in HTML attributes (title="" is an example of an attribute). For instance, ampersands (&) are not allowed to be used in attribute values, so you can’t do something like this:

<h2><a href="#" title="Dog & Pony Show">Dog & Pony Show</a></h2>

(It’s important to note that only the first ampersand in this statement is a problem. The second one is just part of the text as far as the browser’s concerned.)

So what can you do if your post title has one of the illegal characters (less than, greater than, ampersand, double quote and single quote) in it?

The Solution

Savvy WordPress devs know to use esc_attr() when outputting a string into a HTML attribute, which is what we just did above: We output the string “Dog & Pony Show” as the value of the attribute ‘title’. esc_attr() converts illegal characters into their HTML Entities, meaning “&” would be encoded to &amp;, then rendered as the correct character by the browser.

This is where the_title_attribute() comes in.

the_title_attribute() basically does two things with your post title: it runs the title string through PHP’s stripslashes() (a common security procedure), then it gets sent through esc_attr() to encode illegal characters. The effective line in WordPress Core literally looks like this:

// From wp-includes/post-template.php
$title = esc_attr(strip_tags($title));

In the end, your post title is all cleaned up and rendered as valid HTML.

Proper Usage

<h2><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute() ?>" ><?php the_title() ?></a></h2>

//Which will render
<h2><a href="http://my-website.com/dog-pony-show" title="Dog $amp; Pony Show" >Dog & Pony Show</a></h2>

Conclusion

the_title_attribute() is a little-known tool in the developer’s toolbox, but it sure is handy. Be sure to include it in your next Plugin/Theme files.

What other little-known helper functions do you know? Share them in the comments!

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!

Send Emails through WordPress with wp_mail

Standard

This handy function allows you to tell WP to send email. I’m using it to send emails requesting feedback on a customer service site. Its implementation is surprisingly simple.

<?php wp_mail( $to, $subject, $message, $headers, $attachments ); ?>

I created an action that hooked into save_post, and when the post (a support ticket) is updated to “closed” (a custom taxonomy), an email will be sent. It’s amazingly easy.

wp_mail from the WordPress Codex.

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>