Manipulating WordPress strings that print directly

By Tim Priebe on July 13, 2009 at 9:00 am in Development,How-To,html,Technical

Disclosure: This post is for tech-inclined WordPress users, who like to code, or even do it out of necessity. If that doesn’t interest you at all, or you have no idea what I’m talking about, feel free to ignore this post.

We’re big fans of WordPress around here. Unfortunately, many of WordPress’s functions directly print out text and HTML instead of returning a string that can be manipulated directly.

Fortunately, there is a way around that limitation, ob_start. You can feel free to read theĀ  documentation of ob_start, but the short version is that it buffers your output temporarily so you can save it as a string and manipulate it before outputting it.

Let’s look at an example. We’ve added some meta data to a post to display some dates and locations on a page. (Click to enlarge)

Wordpress meta data

Now let’s look at the code.

<?php the_meta(); ?>

The above code outputs the following HTML:

<ul class='post-meta'>

<li><span class='post-meta-key'>July 14, 2009:</span> Marketing Rxpo</li>

<li><span class='post-meta-key'>July 7, 2009:</span> Client Mixer</li>

</ul>

We want two changes. First, we don’t want the colon (:) after the date. Second, we want the spans to have a class of Date instead of post-meta-key. With the code as is, WordPress just displays the info, with no way to change it. So let’s use ob_start instead:

<?php
ob_start();
the_meta();
$out = ob_get_clean();
$out =  str_replace(':</span>', '</span>', $out);
$out =  str_replace('post-meta-key', 'Date', $out);
echo $out;
?>

Here’s the output we get now:

<ul class='post-meta'>
<li><span class='Date'>July 14, 2009</span> Marketing Rxpo</li>
<li><span class='Date'>July 7, 2009</span> Client Mixer</li>
</ul>

Naturally, any string manipulation that can be done in PHP can be performed, this is just a simple example.