Friday, May 8, 2009

WordPress: Modifying Post Content Automatically

Have you ever had the need to have specific content on every single blog post? The way that sounds, I'm sure you'll probably say, "no". But, think about it now, the content does include the HTML. OIC...

So here at work, I've gotten a request to have all links be passed through a link tracker that we built in-house. "Why?" Well, we want to do some sort of testing so we want to keep track of all clicks on links. So that basically means, we need to change all URIs to have the link tracker URI appended by the actual URI that the user put.

Not bad, we can use the WordPress filter, "the_content", and that will get the job done!

Now let's look at the trackURL function:

preg_match_all("/href=\"(.*)\"/",$content, $urls, PREG_PATTERN_ORDER);
$uniqueurls = array_unique($urls[1]);
foreach ($uniqueurls as $url) {
if (!preg_match('/trackerUri.com/', $url)) {
$content = str_replace($url, "http://trackerUri.com/?ab=c/hij&ku=" . $url, $content);
}


It is straightforward; it goes through the content that it is given and finds any "href" references. After those are found, it does a search & replace to insert the new tracker URI before the user-inputed URI.

The rest utilizes WordPress's built-in functions to update the post_content. Easy!

Cheers!


function trackURL($content) {
global $post;
preg_match_all("/href=\"(.*)\"/",$content, $urls, PREG_PATTERN_ORDER);
$uniqueurls = array_unique($urls[1]);
foreach ($uniqueurls as $url) {
if (!preg_match('/trackerUri.com/', $url)) {
$content = str_replace($url, "http://trackerUri.com/?ab=c/hij&ku=" . $url, $content);
}
}
return $content;
}

function trackContent($content) {
global $post;
$pcontent = array();
$pcontent['ID'] = $post->ID;
$pcontent['post_content'] = clicktrackURL($content);
wp_update_post($pcontent);
return $content;
}
add_filter('the_content', 'trackContent');

No comments: