Right now, one of my main projects at work is a totally new theme for the official news outlet for a major corporation. Along with a million other changes, one thing that needs to happen ASAP after switching to the new theme is that the image thumbnail sizes – controlled through Settings › Media in wp-admin – need to be changed.
Of course, being the lazy, automation-obsessed developer that I am, I wanted to find a way to automatically set these thumbnail sizes the instant we changed themes. Fortunately, WordPress fires the after_switch_theme
as soon as the new theme is set; with that action, we can add something like the following to our new theme’s functions.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/** * Change the default image sizes within WordPress. * * In the $image_sizes array, the key corresponds to an image size * while the value is either null (no change) or an array * containing two values: a width and a height. */ function mytheme_set_image_sizes() { // Obviously change these to suit your needs. $image_sizes = array( 'thumbnail' => array( 200, 200 ), 'medium' => null, 'medium_large' => null, 'large' => array( 1024, 1024 ), ); foreach ( $image_sizes as $size => $dimensions ) { if ( null === $image_sizes || 2 !== count( $dimensions ) ) { continue; } // Update the width and height based on $dimensions. update_option( $size . '_size_w', $dimensions[0] ); update_option( $size . '_size_h', $dimensions[1] ); } } add_action( 'after_switch_theme', 'mytheme_set_image_sizes' ); |
Now, as soon as we switch themes, we’ll automatically change the sizes stored in our wp_options
table, based on our $image_sizes
array.
With great power…
Of course, just because you can do something doesn’t mean that you should. If you’re building a new, custom theme, automatically setting thumbnail sizes like this might be super useful. If you’re releasing something publicly, a technique like this starts bordering on “eh, maybe you’re overstepping your bounds as a theme developer.” I’m not here to make that call, I just came here to chew gum and build themes (and I’m all outta gum).
Leave a Reply