Is there a filter I could use to get and change the html output of a link? I would need to add a target="_blank" in some cases.

I'm using the filter post_link to change the url itself where neccessary, but I would need to be able to modify the html part as well. I cannot find correct filter, I ran into a "edit_post_link" filter, but that didn't do the trick as it seems like it's working only at the back-end.

Thanks to everyone who can give me some hint!

  • Are you trying to add it manually in an editor? (If so, Block Editor or Classic?) Or are you trying to filter links that are already in post content? (If so, are you wanting to add a filter that uses something like a regular expression to apply it to certain links, or are you wanting a script to add it to a specific set of links that are already in the database, but don't need to affect future content?)
    – WebElaine
    Aug 21, 2019 at 16:37
  • Thank you very much for your time @WebElaine ! What I would like to modify is the links for articles, with a script that under certain conditions adds "target="_blank". I have already this one, that adjusts the link itself: function pv_external_link($url, $post) { if ($post->ID > 0) { if (get_post_meta($post->ID, 'pv_url', true)) { $url = get_post_meta($post->ID, 'pv_url', true); } } return $url; } add_filter('post_link', 'pv_external_link', 10, 2); And to those links I would need to apply also a target.
    – Pavel
    Aug 22, 2019 at 7:48

1 Answer 1


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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.