0

We have been searching high an low for a plugin, code sample or example of how to remove all external links at the theme filter level but can't seem to find anything online.

We want to keep the external links in the actual post database entry but simply remove them using add_filter() inside the theme's functions.php file so we can add them again when we need to.

We would also need to filter out links for the domain the site is running on - these internal links don't need removing.

We want to remove the link but keep the text inside the link and output it without a link surrounding it.

We have made a start but can't figure out how to exclude internal links or keep the anchor text inside the post.

Any help, code samples, advice, tips or suggestions are greatly appreciated and I thank you in advance.

add_filter( 'the_content', 'filter_the_content_in_the_main_loop' );

function filter_the_content_in_the_main_loop( $content ) {

    if ( is_single() ) {
      $content = preg_replace( '/<a href=\"(.*?)\">(.*?)<\/a>/', '', $content );
    }

    return $content;
}

1 Answer 1

0

You're using the correct approach, minor replacement needed! ..

Simply replace $content = preg_replace('/<a href=\"(.*?)\">(.*?)<\/a>/', "", $content); with $content = preg_replace(array('"<a href(.*?)>"', '"</a>"'), array('',''), $content);

4
  • Hi Hassan. Thank you for your reply. Yes, this worked - many thanks! Now, all we have to figure out is how to allow internal URLs and add an if function for our domain to bypass internal links from this preg_replace. Jan 10, 2018 at 18:02
  • I forgot to ask, do you have a code sample for that if command? Jan 10, 2018 at 18:26
  • I guess it requires a bit of research, .. will get back to this when I get some time! :) Jan 15, 2018 at 7:28
  • an if function for your domain will not work as this is a regular expression. A more reliable method would be to load the content into a DOM/XM parser, HTML tags cannot be correctly parsed with regular expressions and only very primitive but not foolproof processing can be done
    – Tom J Nowell
    Jun 17, 2021 at 20:07

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