How to hide CPT files from media library programmatically

Media items are just like posts with post_type = attachment and post_status = inherit.

when we are on upload.php page, we have two views:

  • List View
  • Grid View

Grid view is populated via JavaScript and list view is extending normal WP_List_Table.

Since it (List view) is using normal post query we can use pre_get_posts to alter the query to hide required media items.

How do we prevent these files from showing in the media library?
Can
we filter by post type?

We can’t just filter the media items by post_type since media items post_type is attachment. What you want is to filter media items by their post_parent's post ids.

add_action( 'load-upload.php' , 'wp_231165_load_media' );
function wp_231165_load_media() {
   add_action('pre_get_posts','wp_231165_hide_media',10,1);
}

function wp_231165_hide_media($query){
    global $pagenow;

// there is no need to check for update.php as we are already hooking to it, but anyway
    if( 'upload.php' != $pagenow  || !is_admin())
        return;

    if(is_main_query()){
        $excluded_cpt_ids = array();//find a way to get all cpt post ids
        $query->set('post_parent__not_in', $excluded_cpt_ids);
    }

    return $query;
}

Check this question to get id’s of a certain post type.

As @tomjnowell pointed out it works for list view but it’s an expensive query.

One thing you can do is that add some meta value while uploading and query against that meta value

Leave a Comment