Using “add_image_size” to register custom image sizes inside plugins not working

There’s several misunderstandings about how WordPress works here.

I noticed that most examples of add_image_size() is done via the
after_setup_theme hook. Which means, for it to register, one has to
switch theme and reactivate the theme.

Firstly, that’s not what it means. The after_setup_theme hook runs on every page load after the theme has been loaded. You can see the sequence of hooks that run on every page load in this old answer (it’s still accurate, but may be missing some newer hooks).

This means that add_image_size() is being run on every page load, and that’s important because it needs to run on every page load.

WordPress is basically a big PHP script that runs every time a page is loaded. So on every page load add_image_size() is used to register the image size in some global scope so that other code in WordPress can use it if an image is being generated or displayed during that request. That image size information is not persistent, so if add_image_size() is not called during a subsequent request WordPress will not have any information about that image size.

So I thought I can register the new custom image sizes using a plugin.
So instead of using the after_setup_theme we will use the
register_activation_hook of the plugin, like so:

register_activation_hook only runs once, when the plugin is activated, so now add_image_size() is only running once which means that on subsequent page loads the image size information being added by that call is no longer available.

So there’s no problem in updating the theme to include a new size with add_image_size(). Once you’ve made that update any future images that are uploaded will be made available in that size. The problem is that add_image_size() does not and cannot resize any existing images. Only future images that are uploaded will be created in the new size.

To handle existing images you will need to use a plugin like Regenerate Thubmnails or the wp media regenerate WP CLI command.

Also, just to address the original wording of the problem, there’s no problem with adding image sizes in plugins. Since plugins are loaded before themes you can even use the after_setup_theme hook from within a plugin. I’m not sure of the earliest or latest hook that add_image_size() can be called in, but init, wp_loaded or plugins_loaded should all work (although plugins_loaded won’t work from within a theme).