'How to remove all external links from database

i have WordPress website with hundreads posts and i need remove all external links from this posts. But also new posts should have external links. So thats reason why i have to remove external links from database and not with script.

Any ideas how to do that?

Edit, i did this script what remove links from posts with ID 1 - 3568

add_filter( 'the_content', 'filter_the_content_in_the_main_loop' );

function filter_the_content_in_the_main_loop( $content ) {

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

    return $content;
}

Is possible add there something, what will send this data to database?



Solution 1:[1]

First need to identify the table and the column which hold the links.
There are 2 types of links : site links and external links.
Site links should be something like http:\\example.com\anything_else
WP standard table for post is wp_posts, but for hiperlinks depends on the customization (can be a column in wp_post or maybe elsewhere. Here is up to u to find)
Assume the table is wp_posts and the column is links then you need to find by pattern and update with nothing those columns.
Mainly the pattern should be start with : http:\\example.com (means links that will be keep as site links and not external)
Translated to sql

update wp_posts 
set links = ''
where links not like 'http:\\example.com%'

Note: WP standard DB is MySql

Update:

function filter_the_content_in_the_main_loop( $content ) {
global $post;    
if ( is_single(range(1, 3568)) ) {
    $content = preg_replace(array('"<a href(.*?)>"', '"</a>"'), array('',''), $content);
    //find the post_id and set new content
    //wp standard way of working with post instead of direct sql
    //this will update each time each post, even the new one after display 
    //(if is in range, so for new one to remain unmodified just keep a lower range, 
    //up to last 100 posts)
    $my_post = array();
    $my_post['ID'] = $post->ID;
    $my_post['post_content'] = $content;
    wp_update_post( $my_post );
}

return $content;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1