Как создать пользовательскую кнопку для визуального редактора, которая добавляет 4 неразрывных пробела? (плагин или простой код)


В визуальный редактор Wordpress (TinyMCE) я хотел бы добавить кнопку, которая при нажатии добавляет четыре неразрывных пробела, например:

    

Я нашел несколько плагинов, которые добавляют кнопки в редактор HTML, но не в визуальный редактор ( этот , например).

Или вообще, было бы неплохо узнать, есть ли плагин или кодируемая (но простая) альтернатива для добавления пользовательских кнопок в визуальный редактор TinyMCE.

Author: its_me, 2012-01-03

2 answers

Я уже продемонстрировал, как вы можете добиться этого в этом вопросе, но я могу объяснить это здесь снова с вашей просьбой. Я протестировал это в Wordpress 3.5, и это работает элегантно. Чтобы избежать того, чтобы этот ответ был длиной диссертации, я добавил комментарии во все коды, чтобы помочь вам понять, что делает каждая функция, и я настоятельно рекомендую вам прочитать и полностью понять их.

Во-первых, в папке вашей темы добавьте папку с именем admin и внутри нее создайте файл class.new_tinymce_btn.php с кодом:

<?php
//wpex_37798_christine_cooper
//class start
class add_new_tinymce_btn {

public $btn_arr;
public $js_file;
/*
 * call the constructor and set class variables
 * From the constructor call the functions via wordpress action/filter
*/
function __construct($seperator, $btn_name,$javascrip_location){
  $this->btn_arr = array("Seperator"=>$seperator,"Name"=>$btn_name);
  $this->js_file = $javascrip_location;
  add_action('init', array(&$this,'add_tinymce_button'));
  add_filter( 'tiny_mce_version', array(&$this,'refresh_mce_version'));

}
/*
 * create the buttons only if the user has editing privs.
 * If so we create the button and add it to the tinymce button array
*/
function add_tinymce_button() {
   if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') )
     return;
   if ( get_user_option('rich_editing') == 'true') {
     //the function that adds the javascript
     add_filter('mce_external_plugins', array(&$this,'add_new_tinymce_plugin'));
     //adds the button to the tinymce button array
     add_filter('mce_buttons', array(&$this,'register_new_button')); 
   }
}
/*
 * add the new button to the tinymce array
*/
function register_new_button($buttons) {
   array_push($buttons, $this->btn_arr["Seperator"],$this->btn_arr["Name"]);
   return $buttons;
}
/*
 * Call the javascript file that loads the 
 * instructions for the new button
*/
function add_new_tinymce_plugin($plugin_array) {
   $plugin_array[$this->btn_arr['Name']] = $this->js_file;
   return $plugin_array;
}
/*
 * This function tricks tinymce in thinking 
 * it needs to refresh the buttons
*/
function refresh_mce_version($ver) {
  $ver += 3;
  return $ver;
}

}//class end
?>

Этот код добавит пользовательские кнопки в визуальный редактор.

Затем в папке вашей темы создайте эти папки adminjs/buttons и внутри создайте этот файл JS spacebutton.js с кодом:

(function() {
    tinymce.create('tinymce.plugins.nextpage', {
        init : function(ed, url) {
            ed.addButton('nextpage', {
                title : 'Space Button',
                image : url+'/images/btn_spacebutton.png',
                onclick : function() {                    
                    var prompt_text = "&nbsp;&nbsp;&nbsp;&nbsp;";
                    var caret = "caret_pos_holder";
                    var insert = "<p>" + prompt_text + " &nbsp;&nbsp;&nbsp;&nbsp;</p> <span id="+caret+"></span>";
                     ed.execCommand('mceInsertContent', false, insert);
                     ed.selection.select(ed.dom.select('span#caret_pos_holder')[0]); //select the span
                     ed.dom.remove(ed.dom.select('span#caret_pos_holder')[0]); //remove the span
                }
            });
        },
        createControl : function(n, cm) {
            return null;
        },
    });
    tinymce.PluginManager.add('nextpage', tinymce.plugins.nextpage);
})(); 

Вам нужно будет добавить изображение для кнопки (/images/btn_spacebutton.png). Приведенный выше код представляет собой довольно простую функцию javascript для того, что происходит при нажатии кнопки.

Теперь вам нужно будет загрузить этот класс кнопок, добавив его в свои функции файл:

//load custom buttons class
require_once (TEMPLATEPATH . '/admin/class.new_tinymce_btn.php');
//create an instance of the class
$t = new add_new_tinymce_btn('|','nextpage',get_bloginfo('template_url').'/adminjs/buttons/spacebutton.js');

Вот и все. Вы должны найти свою новую пользовательскую кнопку в визуальном редакторе. Всякий раз, когда вы хотите добавить больше пользовательских кнопок, просто добавьте новый файл JS с функцией кнопки и загрузите класс кнопки, как показано выше.

 6
Author: Christine Cooper, 2017-04-13 12:37:54

TL;DR, код внизу.

Хорошо, это должно сработать для вас, но это бета-версия. Это работает для меня, но я не проводил никакого тщательного тестирования. Во-первых, он не выводит четыре последовательных объекта &nbsp;; он заикается &nbsp; [space] &nbsp; [space], но, по крайней мере, он сохраняет их как есть при переключении между визуальным и текстовым режимами. Он работает только в визуальном режиме, у меня не было времени, чтобы понять, как заставить его работать в текстовом режиме.

Это входит два файла, назовите их так, как считаете нужным. Я использовал очень образное имя: 4 пространства.:) Кнопка TinyMCE находится в верхнем правом ряду редактора. Он покажет все, что показывает ваш браузер для несуществующих изображений. Это легко изменить в 4spaces.js , строка 8:

image   : url + '/' + 'YOUR_IMAGE_HERE.png'

Измените `YOUR_IMAGE_HERE.png" на файл изображения относительно двух файлов или используйте абсолютный URI, например:

image   : '/path/to/image/YOUR_IMAGE_HERE.png'

Или

image   : 'http://example.com/path/to/image/YOUR_IMAGE_HERE.png'

Я прокомментировал и/или оставил некоторые существующие комментарии по всему PHP, комментарии JavaScript скудны. Вы увидите в разделе заголовка PHP, откуда взят PHP-код, и вид , где возник JavaScript.

Два примечательных кредита, оба перечислены в заголовке PHP: этот WordPress.SE Ответ, который предоставил код, который останавливает TinyMCE (или WordPress, не уверен, какой) от удаления пробелов, и ссылку, приведенную в предыдущем ответе @Alexey, которая, хотя и не критична, помогла мне наткнитесь на решение JS.

Я не смог заставить код в этой ссылке работать, но в конце концов вернулся к ней и нашел самородок, который собрал все это вместе (с некоторыми изменениями, чтобы быть уверенным).

Я думаю, что это примерно все подводит итог. Вот код:

4spaces.php

<?php
/* Plugin Name: 4Spaces
 * Version: 0.1.0
 * Author: AK Ted
 * Author URI: http://akted.com
 * License: GPLv2 or later
 *
 *
 * PHP code adapted & refined from the following two sources:
 * WordPress Codex - http://codex.wordpress.org/TinyMCE_Custom_Buttons#Loading_a_TinyMCE__Plugin
 *
 * WordPress Answers (Stack Exchange) - https://wordpress.stackexchange.com/questions/54398/how-can-i-stop-tinymce-from-converting-my-html-entities-to-characters#answer-54480
 *
 *
 * The JavaScript arose from a lot of trial-and-error, with code [beat into submission...er, I mean] inspired by both of the following sources:
 * tinymce wiki - http://www.tinymce.com/wiki.php/Creating_a_plugin
 * &
 * brett terpstra - http://brettterpstra.com/2010/04/17/adding-a-tinymce-button/
 *
 */

new akt_4spaces();

class akt_4spaces {
    function __construct() {
        add_action('admin_init', array($this, 'init'));
    } // function __construct

    // callback for init
    // sets all the hooks only if user has capability & rich_editing is true 
    function init() {
        // 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_buttons', array($this, 'add_button'));
            add_filter('mce_external_plugins', array($this, 'add_tinymce_plugin'));
            add_filter('tiny_mce_before_init', array($this, 'preserve_entities'));
       }
    } // function init


    // callback for mce_buttons filter
    // adds button to TinyMCE
    function add_button($buttons) {
        array_push($buttons, 'separator', 'four_spaces');
        return $buttons;
    } // function add_button

    // callback for mce_external_plugins filter
    // attaches the JavaScript file to TinyMCE
    function add_tinymce_plugin($plugin_array) {
        $plugin_array['four_spaces'] = plugins_url('/', __FILE__) . '4spaces.js';
        return $plugin_array;
    } // function add_tinymce_plugin


    // callback for tiny_mce_before_init
    // stops TinyMCE (WordPress?) from automatically converting &nbsp; entities
    function preserve_entities( $initArray ) {
        // The odd entries are the entity *number*, the even entries are the entity *name*. If the entity has no name,
        // use the number, prefixed with a hash (for example, the service mark is "8480,#8480").
        $initArray['entities'] = '160,nbsp,' . $initArray['entities'];
        return $initArray;
    } // function preserve_entities

} // class akt_4spaces

4spaces.js

(function() {

    tinymce.create('tinymce.plugins.four_spaces', {
        init : function(ed, url) {
            // Register four_spaces button
            ed.addButton('four_spaces', {
                title   : '4Spaces',
                image   : url + '/' + 'YOUR_IMAGE_HERE.png',
                onclick : function() {
                    ed.execCommand(
                        "mceInsertContent",
                        false,
                        "&nbsp;&nbsp;&nbsp;&nbsp;"
                    );
                }
            });
        }
    });

    // Register plugin
    tinymce.PluginManager.add('four_spaces', tinymce.plugins.four_spaces);

})();

Редактировать: Я забыл упомянуть, для тех, кто не знает, поместите оба этих файла в каталог под /wp-content/plugins/ (путь по умолчанию). Это должно выглядеть что-то вроде /wp-контент/плагины/4 пространства/ или каким бы именем вы ни решили его назвать, затем активируйте его в Admin.

P.S. - Я относительно новичок в ООП, поэтому приветствую любую критику, советы и т.д. от любого, кто просматривает этот ответ.

 5
Author: akTed, 2017-04-13 12:37:50