Rebuild meta data for media items that are missing it

If some of your WordPress media items become corrupted you may need to regenerate the meta data for those items. Fortunately, that’s a straightforward process using this code snippet.


In rare cases, for example after a site migration or content import using a plugin such as WP All Import you may come across issues with your WordPress media library content. If the media files have been correctly imported but information about the alternative image sizes appears to be missing (noticeable because the original image is present but other sizes of thumbnail will not display), it may be because meta data for each media file is missing.

To resolve this, we’re going to loop through the affected Media items and update the meta information on each. WordPress offers a handy wp_generate_attachment_metadata() helper function that will rebuild the meta data for a given attachment and we can then use wp_update_attachment_metadata() to store this information in the wp_postmeta table.

The code snippet below does exactly that, skipping over any .svg images which cannot be resized, although you would have had to already make a modification to allow the upload of SVG files to WordPress’ media library to allow this.


if ( ! function_exists( 'wp_crop_image' ) ) {
    include( ABSPATH . 'wp-admin/includes/image.php' );
}

$attachments = get_posts(
    [
        'post_type' => 'attachment',
        'posts_per_page' => -1,
        'fields' => 'ids',
        'meta_query' => [
            [
                'key' => '_wp_attachment_metadata',
                'compare' => 'NOT EXISTS'
            ]
        ]
    ]
);

foreach($attachments as $attachment_id)
{

    $url = get_attached_file($attachment_id);

    if (strpos($url, '.svg') !== false) continue;

    $attach_data = wp_generate_attachment_metadata($attachment_id, $url);
    wp_update_attachment_metadata( $attachment_id,  $attach_data );

}

You can embed this code within an existing page of your site or you can create a standalone script and run it directly from the browser by adding an additional line of code. Loading wp-load.php gives your script access to all WordPress functions such as get_posts(). Just adjust the path according to the location of your file; the example below should work if the script is located in the root of your site.

require_once('wp-load.php');

A lightweight, intuitive WordPress theme to enable flexible developement.

  • Lighting-fast installer
  • Intuitive SASS structure
  • Bloat-free

Build with Barebones