I’m working on a theme that has a number of image sizes defined correctly using:
add_image_size( 'name', 500, 200, true );
I would like to override these defined sizes from the child theme:
add_image_size( 'new-name', 400, 300, true );
I know I can add new sizes, but if I add the same name i.e:
add_image_size( 'name', 400, 300, true );
Then the parent function call is used – the child one is ignored – adding extra rules adds extra images which will never be used – it’s not so bad, but it’s not efficient.
Is there a function to de-register an added image size?
Cheers!
Ray
The add_image_size( $name, $width, $height, $crop )
function is graceful enough to handle multiple calls using the same $name
. It simply overwrites the existing value:
$_wp_additional_image_sizes[$name] = array( 'width' => absint( $width ), 'height' => absint( $height ), 'crop' => (bool) $crop );
So that means that all you need to do to override the parent Theme’s definition of the custom image size is to ensure that your call to add_image_size()
fires after the parent Theme’s call.
Assuming that the Parent Theme does like so:
function parent_theme_setup() {
add_image_size( 'name', 500, 200, true );
add_image_size( 'new-name', 400, 300, true );
}
add_action( 'after_setup_theme', 'parent_theme_setup' );
Then the parent Theme’s add_image_size()
call fires at the after_setup_theme
hook, at the default priority (i.e. 10
).
(Note: if the calls are not wrapped in a callback, then they fire at the plugins_loaded
hook, at priority 10
.)
Here’s the critical part: the child Theme’s functions.php
file is parsed before the parent Theme’s, so if you use the same hooks to fire your add_image_size()
calls, they’ll get overridden by the parent Theme’s add_image_size()
calls.
The solution is to use a later hook or a lower priority, to ensure that the child Theme’s add_image_size()
call fires after the parent Theme’s.
This should do the trick, regardless of how the parent Theme fires its calls:
function child_theme_setup() {
add_image_size( 'name', 400, 300, true );
}
add_action( 'after_setup_theme', 'child_theme_setup', 11 );
Note that we use the same after_setup_theme
hook, but use a lower priority (i.e. 11
instead of 10
. Callbacks fire in order from higher priority (lower number) to lower priority (higher number), starting with priority 0
. So a callback hooked into priority 11
will fire after a callback hooked into priority 10
.
Note also that the after_setup_theme
hook itself fires after the plugins_loaded
hook, so this callback will still override the parent Theme, even if the parent Theme is _doing_it_wrong()
by not wrapping such calls in an appropriate callback, hooked into an appropriate hook.