Skip to content

Instantly share code, notes, and snippets.

@hugosolar
Last active August 27, 2015 20:57
Show Gist options
  • Save hugosolar/997df2ed51f0833f6566 to your computer and use it in GitHub Desktop.
Save hugosolar/997df2ed51f0833f6566 to your computer and use it in GitHub Desktop.
Add buttons to tinyMCE on Wordpress
(function(){
/*
Este boton deja entre shortcodes el texto seleccionado
para dar el formato requerido por el layout
*/
tinymce.PluginManager.add('custom_button_parallax_content', function( editor, url ) {
editor.addButton( 'custom_button_parallax_content', {
text: '',
icon: 'icn icn-imagen',
title: 'Contenido Parallax',
onclick : function(){
//Obtengo el texto seleccionado
selected = tinyMCE.activeEditor.selection.getContent();
if ( selected ) {
content = '[contenido-parallax]'+selected+'[/contenido-parallax]';
} else {
content = '[contenido-parallax][/contenido-parallax]';
}
//Reemplazo el texto seleccionado por el que tiene los shortcode
tinyMCE.activeEditor.selection.setContent(content);
}
});
});
})();
/*
Aquí lo hice funcionar con Stampa, pero bien se puede utilizar Dashicons de Wordpress para los íconos de los botones
*/
i.mce-i-icn {
font: normal 20px/1 'Stampa';
padding: 0;
vertical-align: top;
speak: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
margin-left: -2px;
padding-right: 2px;
}
.stampa-icon {
cursor: pointer !important;
}
.stampa-icon .icn {
margin: .1rem .2rem;
padding: .3rem !important;
border: 1px solid #333 !important;
border-radius: 3px;
}
(function() {
tinymce.PluginManager.add('custom_button_ead', function( editor, url ) {
//esta lista de iconos tal vez puede ser obtenida de mejor manera para que esté siempre actualizada
var iconList = [
'icn-abierto',
'icn-acto',
'icn-admin',
'icn-alarma',
'icn-ampolleta',
'icn-anuncio',
'icn-archivo',
'icn-asterisco',
'icn-aviso',
'icn-biblioteca',
'icn-bower',
'icn-calendario',
'icn-camara',
'icn-caron',
'icn-caronabajo',
'icn-caronarriba',
'icn-caronizquierda',
'icn-casiopea',
'icn-cerrado',
'icn-ciclo',
'icn-circulo',
'icn-circulolleno',
'icn-clip',
'icn-codigo',
'icn-compartir',
'icn-constel',
'icn-corazon',
'icn-cruzdelsur',
'icn-cuadro',
'icn-cuadrolleno',
'icn-descargar',
'icn-documento',
'icn-email',
'icn-engranaje',
'icn-enlace',
'icn-enlacehorizontal',
'icn-equis',
'icn-ese',
'icn-estorninos',
'icn-estrella',
'icn-etiqueta',
'icn-facebook',
'icn-flecha',
'icn-flechaabajo',
'icn-flechaarriba',
'icn-flechaizquierda',
'icn-flickr',
'icn-grafico',
'icn-hedera',
'icn-hogar',
'icn-imagen',
'icn-impresora',
'icn-ingresar',
'icn-jekyll',
'icn-lapiz',
'icn-lentes',
'icn-less',
'icn-libro',
'icn-lupa',
'icn-lupamas',
'icn-lupamenos',
'icn-mano',
'icn-manoabajo',
'icn-manoarriba',
'icn-manoizquierda',
'icn-mapa',
'icn-mapamas',
'icn-marcador',
'icn-mas',
'icn-menos',
'icn-menu',
'icn-movil',
'icn-nav',
'icn-navabajo',
'icn-navarriba',
'icn-navizquierda',
'icn-noticias',
'icn-ojo',
'icn-ordenhorizontal',
'icn-ordenvertical',
'icn-palabra',
'icn-parlante',
'icn-parrafo',
'icn-pc',
'icn-perfil',
'icn-prohibir',
'icn-rama',
'icn-refrescar',
'icn-reloj',
'icn-rss',
'icn-salir',
'icn-sitemap',
'icn-soundcloud',
'icn-stampa',
'icn-subir',
'icn-tablet',
'icn-tiempo',
'icn-trabajo',
'icn-travesia',
'icn-twitter',
'icn-usuario',
'icn-usuariomas',
'icn-usuariomenos',
'icn-usuarios',
'icn-vimeo',
'icn-vineta',
'icn-visto',
'icn-youtube'
];
//construimos la tabla con todos los iconos
var gridHtml = '<table role="presentation" cellspacing="0" class="mce-stampa"><tbody>';
var width = 25;
var height = Math.ceil(iconList.length / width);
for (y = 0; y < height; y++) {
gridHtml += '<tr>';
for (x = 0; x < width; x++) {
var index = y * width + x;
if (index < iconList.length) {
var chr = iconList[index];
gridHtml += '<td title="' + chr[1] + '"><div tabindex="-1" title="' + chr[1] + '" role="button" style="">' +
'<a href="#'+chr+'" class="stampa-icon"><i class="icn '+chr + '"></i></a></div></td>';
} else {
gridHtml += '<td />';
}
}
gridHtml += '</tr>';
}
gridHtml += '</tbody></table>';
//Añadimos el boton como un menú
editor.addButton( 'custom_button_ead', {
text: '',
type: 'menubutton',
icon: 'icn icn-stampa',
title : 'Insertar Stampa',
menu: [ {
//Primer elemento del menú inserta un ícono en el editor
text: 'Insertar ícono',
onclick: function() {
win = editor.windowManager.open({
title: 'Insertar icono Stampa',
body: [
{
type: 'container',
//se le asigna el listado de todos los iconos que construimos mas arriba
html: gridHtml,
style: 'font-family: "Stampa"', //le decimos que el elementos tiene el font-family de los iconos
onclick: function(e) {
var target = e.target;
//obtenemos la clase del iconos seleccionado
var classbutton = jQuery(e.target).parent().attr('href').replace('#','');
//se inserta en el editor en forma de shortcode
editor.insertContent('[icn icono=' + classbutton + ']');
//cerramos la ventana activa
if (!e.ctrlKey) {
win.close();
}
},
}
],
onsubmit: function(e) {
// por el momento no hacemos nada al hacer submit
}
});
}
},
{
//el segundo elemento del menú inserta un titulo con un ícono
text: 'Insertar título + icono',
onclick: function(){
win = editor.windowManager.open({
title: 'Insertar título + ícono Stampa',
body: [
{
type: 'container',
//utilizamos el mismo listado de iconos
html: gridHtml,
style: 'font-family: "Stampa"',
onclick: function(e) {
var target = e.target;
var classbutton = jQuery(e.target).parent().attr('href').replace('#','');
//Mostramos el icono seleccionado
jQuery('.selected-icon-stampa').html('<i class="icn '+ classbutton +'"></i>');
//lo asignamos como data al elemento
jQuery('.selected-icon-stampa').data('icon',classbutton);
}
},
{
//listado para seleccionar el tipo de titulo (h1, h2, h3, etc)
type: 'listbox',
label: 'Tipo de título',
name: 'h',
values : [
{ text: 'Título H1', value: 'h1' },
{ text: 'Título H2', value: 'h2' },
{ text: 'Título H3', value: 'h3' },
{ text: 'Título H4', value: 'h4' },
{ text: 'Título H5', value: 'h5' },
{ text: 'Título H6', value: 'h6' }
]
},
{
//un input de texto para escribir el titulo
type: 'textbox',
label: 'Título',
name: 'title'
},
{
type: 'container',
label: 'Ícono seleccionado: ',
style: 'font-family: "Stampa"',
html: '<div class="selected-icon-stampa"></div>'
}
],
onsubmit: function(e) {
//obtenemos la data del icono seleccionado
var icon = jQuery('.selected-icon-stampa').data('icon');
if (icon != undefined) {
//creamos el shortcode
var shortcode = '[titulo icn='+icon+' h='+e.data.h+']'+e.data.title+'[/titulo]';
//lo insertamos
editor.insertContent(shortcode);
}
}
});
}
}]
});
});
})();
<?php
/*
Clase para añadir botones al editor de wordpress
TinyMCE api v4
Wordpress 4.3
*/
class CustomButtons {
private static $instance;
private function __construct(){
$this->init_actions();
}
public static function get_instance(){
if ( !isset(self::$instance) ){
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
public function __clone(){
trigger_error( 'Clone is not allowed.', E_USER_ERROR );
}
public function init_actions() {
add_action('admin_head', array( $this, 'add_tinymce_button' ) );
add_action('admin_enqueue_scripts', array($this, 'custom_button_css' ) );
/*
Shortcodes
*/
add_shortcode( 'icn', array( $this, 'stampa_icon_shortcode' ) );
add_shortcode( 'titulo', array( $this, 'stampa_icon_title_shortcode' ) );
}
public function add_tinymce_button() {
global $typenow;
// check permisos
if ( !current_user_can('edit_posts') && !current_user_can('edit_pages') ) {
return;
}
// check si editor está activo
if ( get_user_option('rich_editing') == 'true') {
add_filter("mce_external_plugins", array( $this, 'add_tinymce_plugin' ) );
//añadimos los iconos a la tercera fila de iconos
add_filter('mce_buttons_3', array( $this, 'register_button' ) );
}
}
public function custom_button_css() {
wp_enqueue_style( 'custom-button-admin', THEME_CSS.'/custom-button.css' );
}
public function add_tinymce_plugin($plugin_array) {
$plugin_array['custom_button_ead'] = THEME_JS.'/custom-button.js';
$plugin_array['custom_button_parallax_content'] = THEME_JS.'/custom-button-parallax.js';
return $plugin_array;
}
function register_button($buttons) {
array_push($buttons, 'custom_button_ead' );
array_push($buttons, 'custom_button_parallax_content' );
return $buttons;
}
public function stampa_icon_shortcode( $atts ) {
$a = shortcode_atts( array(
'icono' => 'icn-stampa'
), $atts );
$out = '<i class="icn '.$a['icono'].'"></i> ';
return $out;
}
public function stampa_icon_title_shortcode( $atts, $content = null ) {
$a = shortcode_atts( array(
'icono' => 'icn-stampa',
'h' => 'h3'
), $atts );
$out = '<'.$a['h'].'><i class="icn '.$a['icono'].'"></i> '.$content.' </'.$a['h'].'>';
return $out;
}
}
$custom_buttons = CustomButtons::get_instance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment