Multiple Featured Images Now Uses Theme Support

I recently posted about my approach to building a WordPress plugin that would provide multiple featured images on any content type. Today, I was looking over the plugin again and realized that I could have done a better job implementing the public API in terms of registering new image pickers. As a reminder, this is how I said you should do that:

<?php

add_action('init', function() {
	if(function_exists('mfi_reloaded_add_image_picker')) {
		mfi_reloaded_add_image_picker('hero-image', array(
			'post_types' => array('post'),
			'labels' => array(
				'name' => __('Hero Image'),
				'set' => __('Set hero image'),
				'remove' => __('Remove hero image'),
				'popup_title' => __('Set Hero Image'),
				'popup_select' => __('Set hero image'),
			),
		));

		mfi_reloaded_add_image_picker('sidekick-image', array(
			'post_types' => array('post'),
			'labels' => array(
				'name' => __('Sidekick Image'),
				'set' => __('Set sidekick image'),
				'remove' => __('Remove sidekick image'),
				'popup_title' => __('Set Sidekick Image'),
				'popup_select' => __('Set sidekick image'),
			),
		));
	}
});

There’s a couple of things I see wrong with this after looking at it again. First, hooking on init is probably too late in some cases. That hook should probably be after_setup_theme. Second, there is already a function that allows for registering support in a theme for a certain piece of functionality: add_theme_support. Finally, I hate the function_exists call there. It is aesthetically unpleasant in my mind.

As such, I’ve changed the plugin to use add_theme_support so there is a new way to use the functionality included:

function register_custom_image_pickers() {
	add_theme_support('mfi-reloaded', array(
		'hero-image' => array(
			'post_types' => array('post'),
			'labels' => array(
				'name' => __('Hero Image'),
				'set' => __('Set hero image'),
				'remove' => __('Remove hero image'),
				'popup_title' => __('Set Hero Image'),
				'popup_select' => __('Set hero image'),
			),
		),
		'sidekick-image' => array(
			'post_types' => array('post'),
			'labels' => array(
				'name' => __('Sidekick Image'),
				'set' => __('Set sidekick image'),
				'remove' => __('Remove sidekick image'),
				'popup_title' => __('Set Sidekick Image'),
				'popup_select' => __('Set sidekick image'),
			),
		),
	));
}
add_action('after_setup_theme', 'register_custom_image_pickers');

You can see the changes in the GitHub repository. Let me know if you have any questions!

Leave a Reply

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