Repair the GUID field for attachments

The guid field in the post table for attachments in 90% of cases points to the file itself - it is the file URL. This field is convenient to use in code to obtain the file link, bypassing WordPress standard function wp_get_attachment_url(). This is for saving resources, more details read here.

However, when moving to another domain, replacing this field for all attachments is a difficult task. To do it quickly, use my small plugin.

/**
 * Plugin Name: Repair Attachment Guid
 * Author: Kama
 * Description: Regenerate attachments "guid" field in posts table in DB. <a class="button" href="?rep_attch_guid">Regenerate</a>.
 * Version: 0.1
 */

if( ! is_admin() ){
	return;
}

if( ! isset( $_GET['rep_attch_guid'] ) ){
	return;
}

add_action( 'plugins_loaded', 'rep_attch_guid' );
function rep_attch_guid() {
	global $wpdb;

	if( ! current_user_can( 'manage_options' ) ){
		return;
	}

	$attchs = $wpdb->get_results( $wpdb->prepare(
		"SELECT SQL_CALC_FOUND_ROWS ID, guid FROM $wpdb->posts WHERE post_type = 'attachment' AND guid NOT REGEXP %s",
		sprintf( "https?://%s.*", preg_quote( $_SERVER['HTTP_HOST'] ) )
	) );

	if( $attchs ){
		$found = $wpdb->get_var( "SELECT FOUND_ROWS()" );

		$done = [];
		foreach( $attchs as $attch ){
			$new_guid = wp_get_attachment_url( $attch->ID );
			$up = $wpdb->update( $wpdb->posts, [ 'guid' => $new_guid ], [ 'ID' => $attch->ID ] );

			if( $up ){
				$done[] = $attch->ID;
			}
		}

		add_action( 'admin_notices', function() {
			echo '<div id="message" class="updated notice is-dismissible">
			<p>Updated ' . count( $done ) . " from $found: " . implode( ', ', $done ) . '</p>
			</div>';
		} );
	}
	else{
		add_action( 'admin_notices', function() {
			echo '<div id="message" class="updated notice is-dismissible"><p>No GUID found for update</p></div>';
		} );
	}
}

Before use, be sure to create a backup of the DB.

An analogous plugin, but for managing all revisions you can find in the article: Performance optimization of WordPress by permalinks (practice)