Query Loop Block: Only Posts With a Featured Image
Limits any Query Loop block with the class "wpide-has-thumbnail" to posts that have a featured image, so image grids never show empty cards.
Opens WPIDE on
Code
$wpide_query_thumbs = array( 'active' => false );
add_filter( 'pre_render_block', function ( $pre, $parsed ) use ( &$wpide_query_thumbs ) {
if ( 'core/query' === $parsed['blockName'] ) {
$classes = isset( $parsed['attrs']['className'] ) ? ' ' . $parsed['attrs']['className'] . ' ' : '';
$wpide_query_thumbs['active'] = false !== strpos( $classes, ' wpide-has-thumbnail ' );
}
return $pre;
}, 10, 2 );
add_filter( 'query_loop_block_query_vars', function ( $query ) use ( &$wpide_query_thumbs ) {
if ( ! $wpide_query_thumbs['active'] ) {
return $query;
}
$meta_query = isset( $query['meta_query'] ) ? (array) $query['meta_query'] : array();
$meta_query[] = array( 'key' => '_thumbnail_id', 'compare' => 'EXISTS' );
$query['meta_query'] = $meta_query;
return $query;
} );
Notes
Add wpide-has-thumbnail to the Query Loop's Additional CSS class(es).
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.