Skip to content

Instantly share code, notes, and snippets.

@davidroyer
Forked from gyrus/shortcodes.php
Created February 3, 2016 20:37
Show Gist options
  • Save davidroyer/0a01a611ce32fc2df6d1 to your computer and use it in GitHub Desktop.
Save davidroyer/0a01a611ce32fc2df6d1 to your computer and use it in GitHub Desktop.
TinyMCE button for WordPress shortcode
<?php
/**
* Skeletal sample shortcode
*/
add_shortcode( 'pilau-sample', 'pilau_sample_shortcode' );
function pilau_sample_shortcode( $atts ) {
extract( shortcode_atts( array(
'text' => ''
), $atts ) );
return $text;
}
/**
* Add TinyMCE buttons for shortcodes
*
* @link http://wp.smashingmagazine.com/2012/05/01/wordpress-shortcodes-complete-guide/
* @link http://brettterpstra.com/adding-a-tinymce-button/
*/
add_action( 'init', 'pilau_tinymce_shortcode_buttons' );
add_filter( 'tiny_mce_version', 'pilau_refresh_tinymce' );
function pilau_tinymce_shortcode_buttons() {
// Don't bother doing this stuff if the current user lacks permissions
if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) )
return;
// Add only in Rich Editor mode
if ( get_user_option( 'rich_editing' ) == 'true' ) {
add_filter( 'mce_external_plugins', 'pilau_tinymce_plugins' );
add_filter( 'mce_buttons', 'pilau_register_tinymce_shortcode_buttons' );
}
}
function pilau_register_tinymce_shortcode_buttons( $buttons ) {
array_push( $buttons, "|", "pilau_sample" );
return $buttons;
}
function pilau_tinymce_plugins( $plugin_array ) {
$plugin_array['pilau_sample'] = get_template_directory_uri() . '/js/tinymce-buttons.js';
return $plugin_array;
}
function pilau_refresh_tinymce( $ver ) {
$ver += 3;
return $ver;
}
/**
* TinyMCE buttons for custom shortcodes
*/
( function() {
tinymce.create( 'tinymce.plugins.PilauSample', {
init: function( ed, url ) {
ed.addButton( 'pilau-sample', {
title: 'Insert Sample',
image: url + '/img/tinymce-sample.png',
onclick: function() {
text = prompt( "Enter text", "" );
ed.execCommand( 'mceInsertContent', false, '[pilau-sample text="' + text + '"]' );
}
});
},
createControl: function( n, cm ) { return null; },
});
tinymce.PluginManager.add( 'pilau-sample', tinymce.plugins.PilauSample );
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment