Skip to content

Instantly share code, notes, and snippets.

@Kovah
Last active January 19, 2017 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kovah/0363e802dc28547cf5ab7de5ee0bba6c to your computer and use it in GitHub Desktop.
Save Kovah/0363e802dc28547cf5ab7de5ee0bba6c to your computer and use it in GitHub Desktop.
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