Convert Gallery Shortcodes to Blocks

Switched from an old theme using the classic editor to a new block theme?

You might discover a few problems like your gallery images are all messed up and cutoff like this :

There’s at least 2 ways you can fix broken galleries after switching from the classic editor to a block theme.

  1. Use the Convert to Blocks plugin by 10up
  2. Use code in your blocks child theme

Note : When using the plugin method, all your posts will be converted to blocks which may cause other problems with other elements you created using the classic editor however it will fix your gallery short code problem.

There’s 2 steps :

Copy and paste the following PHP code to the end of your child themes functions file or custom code snippets plugin.

add_filter('body_class', 'blocks_no_blocks_body_class');
function blocks_no_blocks_body_class($classes) {
	
    if ( has_blocks() ) {
        $classes[] = 'has-blocks';
    } else {
        $classes[] = 'no-blocks';
    }
    return $classes;
}

Copy and paste this CSS into your child themes stylesheet or custom CSS field.

.no-blocks.gallery {
    width: 720px;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: center;
    margin: 0 auto;
}

.no-blocks .gallery img {
    max-width: 100%;
    height: auto;
    flex: 1 1 calc(33.333% - 10px);
    object-fit: cover;
}

The coded solution enables you to at least align your gallery images in 1 column so they fit within your content area without looking stretched.

Use this CSS to style your gallery in columns :

.no-blocks .gallery-columns-3 {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    width: 720px;
    margin: 0 auto;
}

.no-blocks .gallery-columns-3 img {
    width: 100%;
    height: auto;
    object-fit: cover;
}

Now your gallery items should display in columns :

Need More Coding Help?

Book a Consultation

Was This Tutorial Helpful?

Free

$0

Access only to all free tutorials per month.



Monthly

$75

Access to 10 premium tutorials per month.


Tutorial Request


Includes code guarantee and coding support.

Yearly

$500

Access to 15 premium tutorials per month.


Monthly Tutorial Request


Includes code guarantee and priority coding support.