# "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.

- Type: PHP
- Runs: Admin only
- Category: [Media](https://wpide.com/library/category/media/)
- Tags: media-library, usage, audit
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/media-where-is-it-used/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find ""Where Is This File Used?" Box in the Media Library" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
