Search Replace in Database with $wpdb

Advertisement

Introduction Introduction

$wpdb is a global variable which is the Abstraction Object to Access the Database. With the help of $wpdb we can perform the database operation in WordPress. We can perform different database operations.

In this article, I am going to share you how we can use $wpdb to update the URLs from the content.

Top ↑

Issue Issue

Let’s assume that we have a below content:

Lorem Ipsum is simply https://source.com/ text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the https://anothersource.com/, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

In the above content, there are two links these are below:

  • https://source.com/
  • https://anothersource.com/

And we want to replace it with below links:

  • https://destination.com/
  • https://anotherdestination.com/

Top ↑

Solution Solution

Now, Create an array that contains the source URL as key and destination URL as value. Like:

$url_remap = array(
'https://source.com/' => 'https://destination.com/',
'https://anothersource.com/' => 'https://anotherdestination.com/',
);

Now, Use foreach and replace the links with $wpdb as below:

global $wpdb;

foreach ( $url_remap as $from_url => $to_url ) {

// Replace the URLs from the `post_content`
$query = $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, %s, %s)", $from_url, $to_url );
$wpdb->query( $query );

$query = $wpdb->prepare( "UPDATE {$wpdb->postmeta} SET meta_value = REPLACE(meta_value, %s, %s) WHERE meta_key='enclosure'", $from_url, $to_url );
$result = $wpdb->query( $query );
}

Leave a Reply