Last active
January 19, 2017 16:48
-
-
Save Kovah/0363e802dc28547cf5ab7de5ee0bba6c to your computer and use it in GitHub Desktop.
Batch add Custom Buttons to the Wordpress TinyMCE editor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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