"Where Is This File Used?" Box in the Media Library
Adds a box to the media edit screen listing every post and page that shows the file in its content or as its featured image, so you can check before replacing or deleting it.
Opens WPIDE on
Code
add_action( 'add_meta_boxes_attachment', function () {
add_meta_box( 'wpide-media-usage', 'Where this file is used', function ( $attachment ) {
global $wpdb;
$file = wp_basename( (string) get_attached_file( $attachment->ID ) );
$name = preg_replace( '/(-scaled|-rotated)?\.[a-z0-9]+$/i', '', $file );
$in_content = $name ? $wpdb->get_col( $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE post_status IN ('publish','draft','future','private','pending') AND post_type NOT IN ('revision','attachment')
AND ( post_content LIKE %s OR post_content LIKE %s ) LIMIT 50",
'%' . $wpdb->esc_like( $name ) . '%',
'%wp-image-' . (int) $attachment->ID . '"%'
) ) : array();
$as_featured = $wpdb->get_col( $wpdb->prepare(
"SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_thumbnail_id' AND meta_value = %d LIMIT 50",
$attachment->ID
) );
if ( ! $in_content && ! $as_featured ) {
echo '<p>Not found in any content or as a featured image.</p>';
return;
}
echo '<ul>';
foreach ( array_unique( array_merge( $as_featured, $in_content ) ) as $post_id ) {
$labels = array();
if ( in_array( $post_id, $as_featured, false ) ) {
$labels[] = 'featured image';
}
if ( in_array( $post_id, $in_content, false ) ) {
$labels[] = 'in content';
}
printf(
'<li><a href="%s">%s</a> <small>(%s, %s)</small></li>',
esc_url( get_edit_post_link( $post_id ) ),
esc_html( get_the_title( $post_id ) ? get_the_title( $post_id ) : '#' . $post_id ),
esc_html( get_post_type( $post_id ) ),
esc_html( implode( ', ', $labels ) )
);
}
echo '</ul>';
}, 'attachment', 'side', 'low' );
} );
Notes
Searches content for the file name and the image block ID; files used by page builders that store data elsewhere may not be found.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.