Cleaning up the target=”_blank” in your WordPress post

Like many of you I love WordPress and although the system itself returns some beautiful HTML it neglects to offer a good alternative for the good old target=”_blank” for opening a link in a new window or tab.

This ofcourse means that your HTML won’t validate when you’re using a proper HTML specification like XHTML 1.0 Strict or XHTML 1.1. You could switch to a transitional doctype but whatever you do make sure your site validates. Don’t resort to doctype decoration.

I use the following function in my theme’s functions.php.

function rel_external($content)
{
	$regexp = '/\<a[^\>]*(target="_([\w]*)")[^\>]*\>[^\<]*\<\/a>/smU';
	if( preg_match_all($regexp, $content, $matches) ){
		for ($m=0;$m<count($matches[0]);$m++) {
			if ($matches[2][$m] == 'blank') {
				$temp = str_replace($matches[1][$m], 'rel="external"', $matches[0][$m]);
				$content = str_replace($matches[0][$m], $temp, $content);
			} else if ($matches[2][$m] == 'self') {
				$temp = str_replace(' ' . $matches[1][$m], '', $matches[0][$m]);
				$content = str_replace($matches[0][$m], $temp, $content);
			}
		}
	}
	return $content;
}

add_filter('the_content', 'rel_external');

With this snippit I remove any target=”_self” attributes and replace the target=”_blank” with rel=”external”. Optionally you could replace this with a rel=”external nofollow” to prevent you from ‘leaking’ Pagerank. I then use the following script by Jeff Starr to add the target=”_blank” function via javascript.

// Open External Links as Blank Targets via Unobtrusive JavaScript
// http://perishablepress.com/press/2007/11/20/open-external-links-as-blank-targets-via-unobtrusive-javascript/

function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (
			anchor.getAttribute("href") && (
			anchor.getAttribute("rel") == "external" ||
			anchor.getAttribute("rel") == "external nofollow" ||
			anchor.getAttribute("rel") == "nofollow external" )
			)
		anchor.target = "_blank";
	}
}

jQuery(document).ready(function() {
	externalLinks();
});

This works like a charm and I use it for almost every website I develop.

2 thoughts on “Cleaning up the target=”_blank” in your WordPress post”

Comments are closed.