How to Automatically Download and Localize External Images in WordPress Posts: functions files


Write a WordPress image localization function. This function will automatically download external images to the media library when publishing or updating articles.
 <? php
//functions.php

/**
Download external images to your local media library
*/
Function download_external_images ($post_id) {
//Get the content of the article
$Post = get_post ($post_id);
$Content = $post- > post_content;

If the content is empty, return
If (empty ($content)) {
Return;
}

Match all image tags
$Pattern = '/< img [^ >] + src =[\'"]([^\'"]+)[\'"][^>]*>/ i';
preg_match_all ($pattern, $content, $matches);

If (empty ($matches [1])) {
Return;
}

//Get the site URL
$site_url = get_site_url ();
$updated = false;

Foreach ($matches [1] as $image_url) {
//Skip the pictures on this site
If (strpos ($image_url, $site_url)! == false) {
Continue;
}

//download the picture
$Tmp = download_url ($image_url);
If (is_wp_error ($tmp)) {
Continue;
}

//Get file information
$file_array = array (
'Name '= > basename ($image_url),
'tmp_name '= > $tmp
);

//Check the file type
$file_type = wp_check_filetype ($file_array ['name']);
If (! $file_type ['type']) {
Unlink ($tmp);
Continue;
}

//Add the image to the media library
$attachment_id = media_handle_sideload ($file_array, $post_id);

If (is_wp_error ($attachment_id)) {
Unlink ($tmp);
Continue;
}

//Get a new image URL
$new_url = wp_get_attachment_url ($attachment_id);

//Replace the image URL in the content
$Content = str_replace ($image_url, $new_url, $content);
$updated = true;
}

//If there is an update, save the article content
IF ($updated) {
wp_update_post (array (
'ID '= > $post_id,
'post_content '= > $content
));
}
}

//Add a hook to trigger when saving the article
add_action ('save_post', 'download_external_images', 10,1);

/**
* Add image failed to download error handling
*/
Function handle_download_error ($error_msg, $error_code, $error_data, $file) {
error_log ("Image download failed : " . $ error_msg);
Return new WP_Error ($error_code, $error_msg, $error_data);
}
add_filter ('wp_handle_upload_error', 'handle_download_error', 10,4);
Main function description:
Auto-trigger: automatically runs when an article is saved or updated

Image detection: Use regex (regular expression) to match all images in the content of the article

Localization:

Skip the pictures on this site
Download external images
Add to Media Library
Update the image URL in the article content
Error handling:

Check file type
Handling failed to download
Log errors
How to use:
Add the code to the theme's functions.php file
When you publish or edit an article, the function runs automatically
External images are automatically downloaded and replaced with local URLs.

Performance optimization:

Only process external pictures.
Working with files with WordPress build-in function
Update article content only when there are changes
Add error handling to avoid interruptions

Notes:

Make sure WordPress has write permissions
Check that the media library has sufficient storage space
You may need to adjust the PHP execution time limit
It is recommended to test in the testing environment first

WordPress moved to a new domain MySQL processing


Let me share something from my trenches. Back in 2025, I botched my first WordPress migration so badly that I spent three sleepless nights fixing the mess. Now, after countless successful migrations, I've learned that the MySQL database is like a delicate ecosystem – disturb it carelessly, and things fall apart fast.

Look, moving WordPress isn't just dragging files from one place to another. The real magic (or nightmare) happens in the database. I've seen perfectly good sites turn into digital ghost towns because someone forgot to update a few database entries. Trust me, you don't want your client calling at 3 AM because their site looks like Swiss cheese.

The Database Maze: Finding Your Way Around

You know what's funny? WordPress spreads domain info across its tables like my kids spread toys around the house. Through trial and error (mostly error), I've found these tables need the most attention:

wp_options    -- The control center
wp_posts      -- Where content lives
wp_postmeta   -- The behind-the-scenes stuff
wp_links      -- Old school, but still important

Sometimes I'll grab a coffee and stare at these tables for minutes, planning my attack route. One wrong move with these absolute URLs, and... well, let's not go there.

The Money Queries: Getting Things Done

After messing up probably hundreds of times, here are the queries that haven't failed me yet:

-- The bread and butter of domain updates
UPDATE wp_options 
SET option_value = replace(option_value, 'old-site.com', 'new-site.com') 
WHERE option_name IN ('home', 'siteurl');

-- Because content needs love too
UPDATE wp_posts 
SET post_content = replace(post_content, 'old-site.com', 'new-site.com');

-- Don't forget these pesky GUIDs
UPDATE wp_posts SET guid = replace(guid, 'old-site.com', 'new-site.com');
UPDATE wp_posts SET post_content = replace(post_content, 'old-site.com', 'new-site.com');
UPDATE wp_posts SET post_excerpt = replace(post_excerpt, 'old-site.com', 'new-site.com');-- Keep things tidy
OPTIMIZE TABLE wp_posts, wp_postmeta, wp_options;

-- The attachment shuffle
UPDATE wp_postmeta SET meta_value = replace(meta_value, 'old-site.com', 'new-site.com');
-- categories and tagsUPDATE wp_terms SET slug = replace(slug, 'old-site.com', 'new-site.com');UPDATE wp_term_taxonomy SET description = replace(description, 'old-site.com', 'new-site.com');-- commentUPDATE wp_comments SET comment_content = replace(comment_content, 'old-site.com', 'new-site.com');UPDATE wp_comments SET comment_author_url = replace(comment_author_url, 'old-site.com', 'new-site.com');
UPDATE wp_wpil_report_links
SET clean_url = REPLACE(clean_url, 'old-site.com', 'new-site.com')
WHERE clean_url LIKE '%old-site.com%';

UPDATE wp_wpil_report_links
SET raw_url = REPLACE(raw_url, 'old-site.com', 'new-site.com')
WHERE raw_url LIKE '%old-site.com%';


Gaming site SEO: A battle that requires more "scheming"


  • Recently, I read an interesting case study about the SEO strategy of gambling and casino websites. After reading it, I found that this is really not a simple job. It is very different from the SEO methods in other industries. To put it bluntly, this industry is too deep in water, the competition is so fierce that people's scalp pins and needles, and the supervision is so strict. With the old SEO method, it will definitely suffer. It must be a more refined and targeted style of play.


    Industry particularity: survival game under high pressure


    First of all, this industry has its own "high pressure" attribute. Competition? It is simply the Red Sea in the Red Sea. Each family is throwing money and robbing resources. It is impossible to play without making some real things. Also, the regulatory policies of various countries and regions are called meticulous, stepping on thunder without paying attention. Take key words as an example, some words you may not be able to use if you want to use them, and you will be sentenced to "death." Moreover, the players' mind is quite unpredictable. Some people come directly to specific games, some just want to find a place to have fun, and others are purely for bonus hunter.

    Therefore, you have to meet all kinds of needs in all directions.


    SEO Challenge: treading on thin ice


    In gambling SEO, keyword competition is a common occurrence. Those words that are related to gambling and casinos are all hot cakes, and everyone wants to rob them. Therefore, you must find another way to find those words with high conversion rate but relatively less intense competition. Besides, content creation is really a technical job. You have to write high-quality and attractive things so that players are willing to watch, but you have to be careful not to violate those messy regulations.

    After all, trust and authority are the lifeblood of the gambling industry. You have to make people feel that you are reliable and professional, so that people can play with you with confidence. In addition, the technical details of website speed, mobile end experience and website architecture have to be done well, not at all slow. Also, the external chain is especially difficult to handle. You can't just find a website to cooperate. It must be of high quality and creative. Don't let people see through your purpose at a glance.


    SEO strategy: step by step, steady and steady


    So, how to break the game? I think we can start from the following aspects:


    Keyword Research: Don't just stare at those "hot words" with high traffic, dig up more Long Tail keywords and niche keywords. For example, "where can I play the latest slot machines," "what are the preferential activities in local casinos" and "where can I try casino games for free." At the same time, we have to analyze the strategies of competitors to see what words they are using, and then find the gaps that can be used.


    Content optimization: Don't just advertise, but make some useful content for players, such as game guides, casino reviews, strategy analysis, industry news, etc. Of course, don't forget to optimize these content, add keywords naturally, and don't let users think you are hard to plug. Use more pictures and videos to make the content more vivid and interesting, and update it regularly to keep it fresh.


    Technical SEO: website speed is the foundation, faster, faster. The mobile end experience is also very important, now who is still holding the computer to play? The website structure must be clear, convenient for search engine scraping. Security issues cannot be ignored, HTTPS must be arranged.


    Link building: Don't spread the net everywhere, but find high-quality related websites to cooperate. Write high-quality content and let others take the initiative to link you. Actively participate in industry forums and communities to get acquainted. You can also engage in some public relations activities and news releases to increase exposure.


    Local SEO: If you have brick and mortar stores, be sure to do local SEO to attract local users. Register the merchant information, optimize Google's My Merchant profile, and strive for more local reviews and ratings.


    Data analysis: Don't do it blindly, use analysis tools to track website traffic, keyword ranking, and understand user behavior. Adjust the SEO strategy according to the data so that every step has a basis.


    Case Analysis: Real Knowledge from Actual Combat


    How to apply these strategies:


    How to Get Accurate Traffic by Mining Long Tail Keywords?


    How to establish the authority of the website through high-quality content?


    How to use technology SEO to improve website performance and user experience?


    How to build a strong external link network through creative link construction?