Skip to content

Instantly share code, notes, and snippets.

@crissoca
Last active May 16, 2018 17:19
Show Gist options
  • Save crissoca/79524b013410c8bff092 to your computer and use it in GitHub Desktop.
Save crissoca/79524b013410c8bff092 to your computer and use it in GitHub Desktop.
Rebuilds WordPress image metadata after a manual media library migration
<?php
//Source: http://www.adam-makes-websites.com/discoveries/fixing_messed_up_image_attachments_in_wordpress_that_have_no_postmeta_values
function fixWPImageMetaData() {
// Notes:
// 1) This function will not alter existing meta entries for your images. The function is to ADD meta data for the images
// without it due to manually importing them or some other kind of mess-up in your wordpress wp_postmeta table.
// 2) Always remember to take a full database backup before each run of the function!
// 3) Although only tested on fairly recent WP versions it may work as far back as v1.5+. Give it a go and let me know!
// Usage:
// 1) Backup your database. Also look in wp_postmeta with a database tool. Order by meta_id DESC and make a note of the highest
// meta_id value at the top of the results. This is useful in case you want to undo changes added by the function.
// Remember, this function only updates the wp_postmeta table.
// 2) First reference the function in a page within the frontend of your theme!
// You can call the function within your themes functions.php file but don't refresh an admin page as the relative
// paths will be wrong and the function will fail.
// 3) With the $test_run set to true check the path settings and then run the file and read the debug output on screen.
// If it looks all ok and the file paths correct set test_run to false and run once more!
// 4) After running the function once with the $test_run set to false comment out your call to the function and check your
// results! Hopefully new images or images with their thumbnails will now appear in the Media page of the WP admin.
// settings
$test_run=true; // set this to false AFTER your happy with the results
// the paths - check these and ensure they both end with a forward slash!
$full_url_to_upload_folder_root=array("http://localhost/wp-content/uploads/", "http://localhost/wordpress/wp-content/uploads/"); // this will definitely need updating for your install!
$local_path_to_uploads="wp-content/uploads/"; // this is the path relative to the base WP folder
global $wpdb;
$sql = "select ID from {$wpdb->posts}
where post_type = 'attachment'
and post_mime_type like 'image/%'";
$images = $wpdb->get_col($sql);
foreach ($images as $id) {
$run=false;
echo "<br>Reading meta for attachment ID: ".$id."...<br>";
$meta = wp_get_attachment_metadata($id);
if (!$meta) {
echo "No meta data for attachment ID: ".$id."...<br>";
$file = get_attached_file($id);
if (empty($file) || $file==""){
// if this fails try to get filename from post and check it exists
$sql2 = "select guid from {$wpdb->posts}
where ID=$id";
$imageSearch = $wpdb->get_col($sql2);
if ( !empty($imageSearch) && $imageSearch[0]!=""){
$foundImage=$imageSearch[0];
$foundImage=str_replace($full_url_to_upload_folder_root,"",$foundImage);
// check it exists!
if (file_exists($local_path_to_uploads.$foundImage)){
$run=true;
$file=$local_path_to_uploads.$foundImage;
echo "I've checked for file manually ('".$local_path_to_uploads.$foundImage."') and it exists so can resolve!<br>";
}else{
echo "I've checked for file manually ('".$local_path_to_uploads.$foundImage."') but doesn't exist at this location so ignoring.<br>";
}
}
}else{
$run=true;
}
if ($run===true&&$test_run!==true) {
echo "Adding new meta data for attachment ID: ".$id."...<br>";
// add first meta entry with image properties...
$info = getimagesize($file);
$file_for_insert=str_replace($local_path_to_uploads,"",$file);
$meta = array (
'width' => $info[0],
'height' => $info[1],
'hwstring_small' => "height='{$info[1]}' width='{$info[0]}'",
'file' => ($file_for_insert),
'sizes' => array(), // thumbnails etc.
'image_meta' => array(), // EXIF data
);
update_post_meta($id, '_wp_attachment_metadata', $meta);
// add a second meta entry for the local path to the file...
update_post_meta($id, '_wp_attached_file', $file_for_insert);
}
}
}
}
//Source: http://wordpress.stackexchange.com/questions/9870/how-do-you-create-a-virtual-page-in-wordpress
add_action( 'init', 'wpse9870_init_internal' );
function wpse9870_init_internal()
{
add_rewrite_rule( 'new-thumb', 'index.php?wpse9870_api=1', 'top' );
}
add_filter( 'query_vars', 'wpse9870_query_vars' );
function wpse9870_query_vars( $query_vars )
{
$query_vars[] = 'wpse9870_api';
return $query_vars;
}
add_action( 'parse_request', 'wpse9870_parse_request' );
function wpse9870_parse_request( &$wp )
{
if ( array_key_exists( 'wpse9870_api', $wp->query_vars ) ) {
fixWPImageMetaData();
exit();
}
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment