Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Batch add Custom Buttons to the Wordpress TinyMCE editor
<?php
/**
* Module loader for custom buttons that need advanced TinyMCE support
* @link https://kovah.me/en/programmatically-add-custom-buttons-wordpress-tinymce-editor/
*/
function kvh_tinymce_module_loader()
{
$tinymce_modules = [
'youtube_player' => 'youtube-player',
'review' => 'review',
'usercard' => 'usercard',
'cta' => 'cta',
];
$i = 10;
foreach ($tinymce_modules as $module => $directory) {
$module = 'kvh_' . $module . '_btn';
// Hooks your functions into the correct filters
add_action('admin_head', function () use ($module, $directory, $i) {
// Check user permissions
if (!current_user_can('edit_posts') && !current_user_can('edit_pages')) {
return;
}
// Check if WYSIWYG is enabled
if ('true' == get_user_option('rich_editing')) {
// Load the JS file that handles the button
add_filter('mce_external_plugins', function ($plugin_array) use ($module, $directory) {
$plugin_array[$module] = get_template_directory_uri() . "/modules/$directory/_editor.js";
return $plugin_array;
}, $i);
// Add the button to the editor UI
add_filter('mce_buttons', function ($buttons) use ($module) {
array_push($buttons, $module);
return $buttons;
}, $i);
}
});
// Load the shortcode handler
require(get_template_directory() . "/modules/$directory/_shortcode.php");
// Unset the variables
unset($module, $file);
$i++;
}
}
kvh_tinymce_module_loader();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.