WordPress Media Buttons

If you know Wordpress, you know it is a great publishing platform. For a particular plugin I wanted to build I started looking at how to add one of those little icons you have access while writing a post, e.g. ‘Add an Image’, etc.

I was looking at how other plugins do this and found this code:

function wp_myplugin_media_button() {
	$context = __('Add media: %s');
	$wp_myplugin_media_button_image = '/path/media_button.gif';
	$wp_myplugin_media_button = '<a href="media-upload.php?type=wp_myplugin&amp;TB_iframe=true" class="thickbox">
  <img src='".$wp_myplugin_media_button_image."' /></a>".' %s';
	return sprintf($context, $wp_myplugin_media_button);
}
add_filter('media_buttons_context', 'wp_myplugin_media_button');

But when I tried this in my plugin something weird happened. If both my plugin and the one from where I took this code were active, then only the button from the other plugin would appear. If I disabled the second one then it worked. Why, oh why? After struggling a bit I found the answer.

The way the function is receiving the context is not correct. Both functions are asking for the default “context” (this is the media buttons themselves) and then adding something to it. The correct way to receive the context is to have it as an argument of the function. In that way it can be updated without a problem. Example follows:

function wp_myplugin_media_button($context) {
	$wp_myplugin_media_button_image = '/path/media_button.gif';
	$wp_myplugin_media_button = '<a href="media-upload.php?type=wp_myplugin&amp;TB_iframe=true" class="thickbox">
  <img src='".$wp_myplugin_media_button_image."' /></a>".' %s';
	return sprintf($context, $wp_myplugin_media_button);
}
add_filter('media_buttons_context', 'wp_myplugin_media_button');

Update: if you want to add the button to the end of the media button list just append the %s first, e.g.:

function wp_myplugin_media_button($context) {
	$wp_myplugin_media_button_image = '/path/media_button.gif';
	$wp_myplugin_media_button = ' %s' . '<a href="media-upload.php?type=wp_myplugin&amp;TB_iframe=true" class="thickbox">
  <img src='".$wp_myplugin_media_button_image."' /></a>";
	return sprintf($context, $wp_myplugin_media_button);
}
add_filter('media_buttons_context', 'wp_myplugin_media_button');

Hope it helps someone. Cheers.