We want to customize lots of things in our WordPress themes, and WordPress gallery style can be one important of those. At first, it may seem easy stuff, but actually it isn’t that easy.
As a developer, you may think of customizing the look of WordPress galleries just by adding some CSS in the style.css
of your theme. But that alone is not gonna work since WordPress automatically adds a default style snippet in the post that contains a gallery, which provides default styles to the gallery, and also overrides all of your CSS code coming from the style.css
or anywhere else.
The code automatically hooked by WordPress in a gallery post looks somewhat like below:
<style type='text/css'> #gallery-1 { margin: auto; } #gallery-1 .gallery-item { float: left; margin-top: 10px; text-align: center; width: 33%; } #gallery-1 img { border: 2px solid #cfcfcf; } #gallery-1 .gallery-caption { margin-left: 0; } /* see gallery_shortcode() in wp-includes/media.php */ </style>
The need to remove the default gallery style
As a user, you may need to do that to customize your galleries look and feel. As a developer, you may need to do that to make your galleries match the theme styles. You might have already seen some professional themes providing custom Gallery styles.
In order to make galleries adopt our custom styles, we’ve to stop WordPress adding this bit of code into the gallery posts.
Removing the default CSS code from gallery posts
Now we know that the hurdle in our way to customize our gallery look is the auto-added style
snippet. Once we restrict the addition of this default style, we are almost done.
Well, this will only take a single line of code. Add the below code in functions.php
file of our WordPress theme:
add_filter( 'use_default_gallery_style', '__return_false' );
The above hook tells WordPress not to add that style code segment in the post containing a gallery.
Now, you have to save the functions.php
file and then view a gallery post. The galleries must be rendering without styles added to them OR they must be adopting the CSS if you’ve added in the style.css
of the theme. Hope it served well :)