Set Default Number of Columns for WordPress Gallery

WordPress version 2.5 introduced a very useful feature for many bloggers: a built-in gallery system. All your photos uploaded to a specific Post or Page and using the Gallery Shortcode, [gallery], will display a set of thumbnails anywhere in your Post or Page. When used with most WordPress themes, the default 3-column thumbnail display works very well. But for some WordPress themes, such as this one, the default 3-column thumbnail display has too much space between each thumbnail. WordPress-Gallery-4-columnsFortunately, you can make the Gallery display 4-or-more-columns by adding columns=4 inside the Gallery Shortcode like [gallery columns=4]. That can be a pain because you have to remember to do each time you add a Gallery to a Post or Page and all your prior Posts or Pages will continue to be 3-columns. So how do you reset the default number of Gallery thumbnails? Fortunately a Google search led me to this post by Zeo who has a solution in which you enter the code below in your functions.php file:

[sourcecode language=”PHP”]
function gallery_columns($content){
$columns = 2;
$pattern = array(
$replace = ‘stripslashes(strstr("1", "columns="$columns"") ? "1" : "[gallery 2 4 columns="$columns"]")’;

return preg_replace($pattern, $replace, $content);

add_filter(‘the_content’, ‘gallery_columns’);

Make sure you change $columns = 2; to however many columns you like. Also the above code has to be wrapped in &#lt;?php and ?> or it will not work.

Very nice and elegant. This way if you change themes, you don’t have to manually edit every Post or Page to adjust how the Gallery column thumbnails display. Thanks Zeo.

Leave a Reply

Your email address will not be published. Required fields are marked *