How to add a target to a link

If you use the filter “the_content” you can use a combination of preg_... statements to loop through all links, adding target=”_blank” to those matching your specific requirements. You can add this filter to your functions.php, or to select page,post, or category templates .

add_filter( 'the_content', 'ex1_the_content_filter' );
function ex1_the_content_filter($content) {
    // finds all links in your content
    preg_match_all('/(\<a href=.*?a>)/',$content,$matches, PREG_SET_ORDER);

    // loop through all matches
    foreach($matches as $m){
        // potential link to be replaced...
        $toReplace = $m[0];

        // if current link does not already have target="{whatever}"
        // You can add whatever additional "IF" you require to this one
        if (!preg_match('/target\s*\=/',$toReplace)){
            // adds target="_blank" to the current link
            $replacement = preg_replace('/(\<a.*?)(\>)(.*?\/a\>.*?)/','$1 target="_blank"$2$3',$toReplace);
            // replaces the current link with the $replacement string
            $content = str_ireplace($toReplace,$replacement,$content);
        }
    }
      return $content;
}