Skip to content

Instantly share code, notes, and snippets.

@joshapgar
Created April 7, 2017 12:59
Show Gist options
  • Save joshapgar/d07d79404346de0ea7653c1cca3bf5a1 to your computer and use it in GitHub Desktop.
Save joshapgar/d07d79404346de0ea7653c1cca3bf5a1 to your computer and use it in GitHub Desktop.
Link Button Shortcode with TinyMCE Button
<?php
/****************************
* Register Shortcodes
****************************/
add_action( 'init', 'register_shortcodes');
function register_shortcodes(){
add_shortcode('linkbutton', 'linkbutton_function');
}
function linkbutton_function( $atts, $content = null ) {
extract( shortcode_atts( array(
'url' => '#'
), $atts ) );
return '<a id="short-button" href="'.$url.'">'.do_shortcode($content).'</a>';
}
/*****************************
* Register TinyMCE Button
******************************/
function link_button( $buttons ) {
array_push( $buttons, "link_button" );
return $buttons;
}
/******************************
* Add TinyMCE Javascript
******************************/
function add_plugin( $plugin_array ) {
$plugin_array['link_button_script'] = get_template_directory_uri() . '/library/js/libs/linkbutton.js';
return $plugin_array;
}
/**********************************
* Register Custom Button Functions
**********************************/
function bones_linkbutton() {
if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') ) {
return;
}
if ( get_user_option('rich_editing') == 'true' ) {
add_filter( 'mce_external_plugins', 'add_plugin' );
add_filter( 'mce_buttons', 'link_button' );
}
}
add_action('admin_init', 'bones_linkbutton');
// Style the button with a dashicon icon instead of an image
function bones_tinymce_button_dashicon() {
?>
<style type="text/css">
.mce-i-link_button:before {
content: '\f116';
display: inline-block;
-webkit-font-smoothing: antialiased;
font: normal 25px/1 'dashicons';
vertical-align: top;
}
</style>
<?php
}
add_action( 'admin_head', 'bones_tinymce_button_dashicon' );
?>
(function() {
// Register buttons
tinymce.create('tinymce.plugins.LinkButtons', {
init: function( editor, url ) {
// Add button that inserts shortcode into the current position of the editor
editor.addButton( 'link_button', {
title: 'Link Button',
icon: false,
onclick: function() {
// Open a TinyMCE modal
editor.windowManager.open({
title: 'Link Button',
body: [{
type: 'textbox',
name: 'link',
label: 'Link URL'
},{
type: 'textbox',
name: 'text',
label: 'Button Text'
}],
onsubmit: function( e ) {
editor.insertContent( '[linkbutton url="' + e.data.link + '"]'+ e.data.text +'[/linkbutton]' );
}
});
}
});
},
createControl: function( n, cm ) {
return null;
}
});
// Add buttons
tinymce.PluginManager.add( 'link_button_script', tinymce.plugins.LinkButtons );
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment