1

Usually we can filter images in Media > Library by:

  • date
  • by MIME type,
  • and by attached/unattached files

...but I'd like to expand this to a filter by Featured images. This way, we could filter only those images that are set to be Featured of some Post or Custom Post Type.

Do you have some ideas to make it possible?

Thanks,

EDIT

I've added this code in functions.php as per this thread (it won't filter, but it should restrict the results in the Media Library to those images that are Featured, that is, that have _thumbnail_id as meta), but the admin won't load and the server will drop an error.

add_action ('pre_get_posts', 'restrict_media') ;
function
restrict_media ($query)
{

    // get posts with thumbnails
    $args = array (
        'post_type' => 'galleries',
        'post_status' => array ('publish'),
        'posts_per_page' => -1,
        'meta_query' => array (
            array (
                'key' => '_thumbnail_id',
                'compare' => 'EXISTS',
                ),
            ),
        ) ;
    $with_thumbnail = new WP_Query ($args) ;
    // get the IDs of the thumbnails
    $thumbnail_ids = array_map (function ($p) { return (get_post_meta ($p->ID, '_thumbnail_id', true)) ; },
        $with_thumbnail->posts) ;

    // include all thumbnails
    $query->set ('post__in', array($thumbnail_ids)) ;

    return ;
}
1

We can add the Featured option as a fake mime-type with:

add_filter( 'media_view_settings', function( $settings )
{
    $settings['mimeTypes']['wpsefeaturedimage'] = 'Featured';
    return $settings;
});

It will show up like this:

Featured option

Then we can use the posts_where filter and check for our fake mime type:

/**
 * Filter for featured images in the media library popup
 */
add_action( 'pre_get_posts', function( \WP_Query $q )
{
    if( 'wpsefeaturedimage' === $q->get( 'post_mime_type' ) )
    {
        // Remove the fake mime type
        $q->set( 'post_mime_type', '' );
        // Mark this query as featured filtered
        $q->set( 'wpse_filter_featured', true );

        add_filter( 'posts_where', function ( $where, \WP_Query $q )
        {
            if( $q->get( 'wpse_filter_featured' ) )
            {
                global $wpdb;
                // Add 'featured images' restriction to the SQL query
                $where .= " AND {$wpdb->posts}.ID IN 
                    ( SELECT DISTINCT m.meta_value FROM {$wpdb->postmeta} m 
                      WHERE m.meta_key = '_thumbnail_id' 
                    ) ";
            }
            return $where;
        }, 10, 2 );
    }
}, 1 );

We can probably adjust this further.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.