Trouble with WordPress Gallery since update using has_block(‘gallery’

There are 2 core problems here:

  1. has_block('gallery', $post->post_content) should never have worked as there is no block named gallery, the core block is named core/gallery
  2. While the gallery block used an attribute similar to the shortcodes in the past, modern gallery blocks are containers that contain image blocks

As a bonus, the code in your question loads full sized images, I was surprised to see the images load in line by line on a 1Gbit Fibre connection! ( Or that a realty site would disable right click and drag/drop when sharing photos of a property with a spouse via would be super important ).

Instead, I’m not seeing anything in the working version that can’t be done via CSS to the standard gallery markup.

If the goal is to only show the first 9 photos until a button is pressed this can be done with CSS and a small amount of javascript, and a quick PHP filter in multiple ways.

E.g. adding a button on the end of the block markup:

add_filter( 'pre_render_block', 'my_pre_render_block', 10, 2 );
function my_pre_render_block( $pre_render, array $parsed_block ) {
    if ( $parsed_block['blockName'] === 'core/gallery' ) {
        return $pre_render . '<button>Show More</button>';
    return $pre_render;

Or adding a collapsed-gallery class to the gallery blocks by default:

add_action( 'render_block_data', 'my_render_block_data', 1, 3 );
function my_render_block_data( array $parsed_block, $source_block, $parent_block ) : array {
    if ( $parsed_block['blockName'] === 'core/gallery' ) {
        if ( ! isset( $parsed_block['attrs']['className'] ) ) {
            $parsed_block['attrs']['className'] = '';

        $parsed_block['attrs']['className'] = trim( $parsed_block['attrs']['className'] . ' collased-gallery' );
    return $parsed_block;

At this point hiding everything but the first 9 items in the gallery is trivial:

.collapsed-gallery > * {
    display: none;

.collapsed-gallery > *:nth-child(1),
.collapsed-gallery > *:nth-child(2),
.collapsed-gallery > *:nth-child(4),
.collapsed-gallery > *:nth-child(5),
.collapsed-gallery > *:nth-child(6),
.collapsed-gallery > *:nth-child(7),
.collapsed-gallery > *:nth-child(8),
.collapsed-gallery > *:nth-child(9) {
    display: block;

A bit of JS to toggle the collapsed-gallery class when the button is pressed is all that’s left, and this version if future-proof as it doesn’t re-render the gallery blocks HTML from scratch. It even has better performance and accessibility!

This is one example but there are hundreds of other ways to do it, as well as more concise versions of the above.