The marvellous P2 Theme has an interesting feature: write out a plain link, and it magically becomes clickable without explicitly adding the a href tag.
This may not be a big deal if you’re writing posts in the visual WordPress editor rather than HTML, but for those of us who like to write in HTML, it’s just one less thing to worry about.
I was investigating this feature recently, and it turns out WordPress has a built-in function that can do this: they call it make_clickable(), and it works with URIs, FTP, Email addresses and anything starting with www. The function is really easy to use too: it only takes one parameter (a string), and returns the clickable HTML code.
$clickableText = make_clickable($plainText);
Let’s see how to use it in context, using the TwentyThirteen theme.
Take a look at content.php, a template part that prints out full posts among many other things. Find a section with the class of entry-content, and you’ll see something like this:
/* translators: %s: Name of current post */ the_content( sprintf( __( 'Continue reading %s <span class="meta-nav">→</span>', 'twentythirteen' ), the_title( '<span class="screen-reader-text">', '</span>', false ) ) );
This rather convoluted looking block is responsible for printing the_content. On this occasion it also replaces the standard “read more” text with something more palatable, and at the same time translates the whole thing too.
Let’s first simplify this by removing the translation and simply printing the content, including the handsome “Continue Reading” message:
/* simplified content method */ the_content ('Continue reading <span class="meta-nav">→</span>' );
Much easier on the eyes, and does exactly the same for the English version of TwentyThirteen.
Next, let’s do a bit of gentle tweaking: the_content() will print the current posts’s text to the browser. We can’t use this function though because we want to make some modifications before showing it to our audience. Instead we’ll use a related function: get_the_content().
It works *almost* like the_content(), but it will give us raw text without a small filtering applied, so we run the risk of introducing unwanted artefacts on our site. Thankfully it’s easy to apply said filtering manually to get_the_content:
// turn plain URLs in the_content into clickable links $postContent = apply_filters( 'the_content', get_the_content('Continue reading <span class="meta-nav">→</span>')); $postContent = str_replace( ']]>', ']]>', $content ); echo make_clickable($postContent); // the end
And there we have it: first we store the output of get_the_content() in our variable $postContent. Then we apply the filtering so it will deliver the same goodness as the_content() does, and finally we make the $postContent clickable.
The WordPress Codex has more tips and tricks on both functions: