First off, in answer to your second request, that is a setting in the browser. Even though you can detect the browser agent with javascript, there’s no way to open a link in a tab or a new window determined by code. If the blog reader has their browser set to open new windows as tabs within the same window then that’s what will happen even if you want it to open in a new window.
To open a link in a new window (or tab if their browser is set that way), you need to do one of two things dependent upon what level of XHTML compliance you want.
If you want to have XHTML Transitional compliance you can simply add:
target="_blank"
within the anchor tag. This will force the browser clicking the link to open it in a new window (or tab).
If you want to have XHTML Strict compliance, you need to do three things. First, save this code as “external.js” and then upload “external.js” to the root of your WordPress installation using your favorite FTP program:
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.target = "_blank";
anchor.title = (anchor.title != "") ? anchor.title+" (opens in a new window)" : "opens in a new window";
anchor.className = (anchor.className != '') ? anchor.className+' external' : 'external';
}
}
}
window.onload = externalLinks;
Next, make sure that this code is between the <head>
and </head>
tags in your header.php file:
<script type="text/javascript" src="/external.js">
</script>
Finally, in all your anchor tags that you want to open in a new window add:
rel="external"
to all of your anchor tags.
Example: XHTML Transitional
<a href="https://www.somewhere.com/page.php" target="_blank">Open in a new page</a>
Example: XHTML Strict (assuming the other two steps described above are completed)
<a href="https://www.somewhere.com/page.php" rel="external">Open in a new page</a>