15 Apr 2009

WordPress [gallery]: Force x Number of Columns

Does anyone know the easiest way for WordPress [gallery] to force x number of columns display without tampering the core or manually set the columns value to the shortcode?

I could only figure out 2 possible ways:

  1. function / code duplication
  2. Regular expression

If you use [gallery] shortcode without setting the columns value, the default is set to 3. Some WordPress theme can either fit 3 or more column per row or less. Below is an example to force [gallery] columns to 2 to any post or page that uses [gallery] shortcode:

function gallery_columns($content){
        $columns = 2;
        $pattern = array(
                '/(\[gallery(.*?)columns="([0-9])"(.*?)\])/ie',
                '/(\[gallery\])/ie',
                '/(\[gallery(.*?)\])/ie'
        );
        $replace = 'stripslashes(strstr("\1", "columns=\"$columns\"") ? "\1" : "[gallery \2 \4 columns=\"$columns\"]")';

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

add_filter('the_content', 'gallery_columns');

$columns can be set to any numeric value. If [gallery] columns is set to 0, no row breaks will be included.

There are probably some hidden drawbacks to the method above. Feel free to share if you have any other solution.

2 Comments

  1. I didn’t even know this solution, but it seems to work for me. I have been looking for something like this for a few hours now! Thank you!!

    Reply

  2. gaf

    awesome – solved the problem for me too – should be built in to wordpress

    Reply

Leave a Reply to gaf