wpExternalLinks - A Wordpress Plugin

Jul 20 2005 11:22 PM

wpExternalLinksWant some of your links to open in a new window and still have your Wordpress site validate? I did too. But of course, if you use the target attribute in your (X)HTML, you’ll have to forgo that nifty validate link that everyone is so damn proud of.

A little rel, a hint of Javascript, and the Notorious D.O.M.

Basically, I’ve tweaked the functions (or ‘template tags’) wp_get_links and get_links to add rel=”external” to each returned link. The javascript finds all those links and adds target=”_blank” to them. That’s it. No ugly javascript: window.open, onclick events or anything else to prevent your links from being bookmarked, saved, or even followed when javascript is turned off.

Once installed, just change your template tags and you’re ready to go! For example, I wanted my ‘Elsewhere’ links on the sidebar to open in a new window. In my template I added:

<?php wp_get_links_ext(2); ?>

Sounds good. Give it to me.

  1. Get the file. wpExternalLinks 0.1
  2. Place in your plugins directory on your webserver.
  3. Activate in your manager.
  4. Edit template tags.
  5. Add rel=”external” to any links in your site, and they’ll be opened in a new window.

For those of you who just want the javascript:

function externalLinks() {
     if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName('a');
	for (var i=0; i<anchors.length; i++) {
		anchor = anchors[i];			
		var rel = anchor.rel;			
		if (anchor.getAttribute('href') && rel.substring(0,8) == 'external' )
			anchor.target = '_blank';			
	 	}			
	}
window.onload = externalLinks;

So what’s the difference between adding the target in the HTML itself and adding it with javascript? The difference is that the target attribute has been phased out of the (X)HTML standards, but not out of the DOM standards. Simple as that. (X)HTML is responsible for what’s in the browser; not with how the browser should open a link. On the other hand, client-side scripting (viz. Javascript) is perfectly suited to control how the browser behaves.

No ResponsesAdd yours

Wanna be the first to comment? Now's your chance!

You must be logged in to post a comment.