Remove External Links from WordPress posts Using add_filter() in Theme functions.php

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;
}

Topic regex the-content functions filters theme-development Wordpress

Category Web


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);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.