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 = '
".' %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 = '
".' %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' . '
";
return sprintf($context, $wp_myplugin_media_button);
}
add_filter('media_buttons_context', 'wp_myplugin_media_button');
Hope it helps someone. Cheers.
This is actually really helpful, thank you! I was struggling with a similar issue.
This isn't specifically related to your code above, but I'm not sure how to add my custom media button to the end of the media button list instead of the beginning (as this code does). Any suggestions?
Hi k3,
I’ve updated the post to show how to add it to the end of the media button list. It’s actually quite simple.
Cheers,
Nuno
How then could I attach a trigger to an dom element. If I want to do: $('#id').toggle(); on a media button I added. This may be a simple question, but I am hacking my way thru WordPress.. Cheers, Bo