Query Loop Block: Exclude the Current Post
Removes the post being viewed from any Query Loop block that has the class "wpide-exclude-current", for "More posts" sections under articles.
Opens WPIDE on
Code
$wpide_query_exclude = array( 'active' => false );
add_filter( 'pre_render_block', function ( $pre, $parsed ) use ( &$wpide_query_exclude ) {
if ( 'core/query' === $parsed['blockName'] ) {
$classes = isset( $parsed['attrs']['className'] ) ? ' ' . $parsed['attrs']['className'] . ' ' : '';
$wpide_query_exclude['active'] = false !== strpos( $classes, ' wpide-exclude-current ' );
}
return $pre;
}, 10, 2 );
add_filter( 'query_loop_block_query_vars', function ( $query ) use ( &$wpide_query_exclude ) {
if ( ! $wpide_query_exclude['active'] || ! is_singular() ) {
return $query;
}
$exclude = isset( $query['post__not_in'] ) ? (array) $query['post__not_in'] : array();
$exclude[] = get_queried_object_id();
$query['post__not_in'] = array_values( array_filter( array_map( 'absint', $exclude ) ) );
return $query;
} );
Notes
Add wpide-exclude-current under Advanced > Additional CSS class(es) on the Query Loop block, with "Inherit query" turned off.
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.