Skip to content

Instantly share code, notes, and snippets.

@stephenbelyea
Last active June 1, 2016 20:38
Show Gist options
  • Save stephenbelyea/ec02e8efd9906d5bcf1503c9c97f2f2e to your computer and use it in GitHub Desktop.
Save stephenbelyea/ec02e8efd9906d5bcf1503c9c97f2f2e to your computer and use it in GitHub Desktop.
Add MCE shortcode button for WP content editor.
// Register the shortcode.
function my_custom_shortcode( $atts ) {
extract( shortcode_atts(
array(
'arg1' => '',
'arg2' => ''
), $atts )
);
$output = "Whatever you need your shortcode to do...";
return $output;
}
add_shortcode( 'my_shortcode', 'my_custom_shortcode' );
// Add CTA shortcode button.
// init process for registering our button
add_action('init', 'my_shortcode_button_init');
function my_shortcode_button_init() {
//Abort early if the user will never see TinyMCE
if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') && get_user_option('rich_editing') == 'true')
return;
//Add a callback to regiser our tinymce plugin
add_filter("mce_external_plugins", "my_tinymce_plugin_register");
// Add a callback to add our button to the TinyMCE toolbar
add_filter('mce_buttons', 'my_tinymce_button_add');
}
//This callback registers our plug-in
function my_tinymce_plugin_register($plugin_array) {
// Find plugin's JS file in site's theme.
$plugin_array['my_shortcode_button_id'] = get_template_directory_uri() . '/js/my-shortcode-button.js';
return $plugin_array;
}
//This callback adds our button to the toolbar
function my_tinymce_button_add($buttons) {
//Add the button ID to the $button array
$buttons[] = "my_shortcode_button_id";
return $buttons;
}
jQuery(document).ready(function($) {
// Create MCE plugin
tinymce.create('tinymce.plugins.my_shortcode_button_plugin', {
init : function(ed, url) {
// Register button click command
ed.addCommand('my_shortcode_button_insert', function() {
selected = tinyMCE.activeEditor.selection.getContent();
content = '[my_shortcode arg1="" arg2=""]]';
if( selected ){
// Use this to position shortcode with existing selection.
// Eg. Selected copy can be wrapped with the shortcode open/close tags.
content += selected;
}
tinymce.execCommand('mceInsertContent', false, content);
});
var urlEd = url.split('js/');
// Register buttons - trigger above command when clicked
ed.addButton('my_shortcode_button_id', {
title : 'Insert my shortcode',
cmd : 'my_shortcode_button_insert',
// Use image from theme dir (20x20px).
image: urlEd[0] + 'images/my-shortcode-button.png'
});
},
});
// Register TinyMCE plugin
// Params = Button ID, Plugin name (match create's first param).
tinymce.PluginManager.add('my_shortcode_button_id', tinymce.plugins.my_shortcode_button_plugin);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment