7

Wordpress 可视化编辑器添加自定义按钮 - NixonLi博客

 3 years ago
source link: https://www.nixonli.com/15.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

之前介绍了 wordpress文本编辑器快速插入短代码 和 wordpress文本编辑器添加按钮

不过一般来说我们常用的是可视化面板写作 而且像我分享php代码(<pre></pre>) 经常要在可视化和文本模式下进行切换 会经常出错

下文讲的是:在默认编辑器的可视化模式下添加自定义按钮

733a8522c6794b5.jpg

将以下代码复制到主题functions.php里面

1.创建按钮初始函数

add_action('init', 'custom_button');
function custom_button() {
//判断用户是否有编辑文章和页面的权限
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', 'register_button' );
}
}

2.注册按钮

function register_button( $buttons ) {
array_push( $buttons, "|", "video" ); //创建video按钮
array_push( $buttons, "|", "music" ); //创建music按钮,需要添加多个按钮以此形式添加
return $buttons;
}
function add_plugin( $plugin_array ) {
$plugin_array['video'] = get_bloginfo( 'template_url' ) . '/js/video.js'; //对应video按钮js
$plugin_array['music'] = get_bloginfo( 'template_url' ) . '/js/music.js'; //对应music按钮js ,按照本文教程创建相关js文件
return $plugin_array;
}

3.添加短代码

比方说我添加了个video的短代码 (短代码自己完善 这边只做参考)

add_shortcode("video","my_video");
function my_video( $atts, $content=null ) {
return '<div>'.$content.'</div>';
}

4.创建js文件

以创建video.js为例 将创建好的video.js,和video.png一同放进主题 js文件夹

(function() {
tinymce.create('tinymce.plugins.video', {
init : function(ed, url) {
ed.addButton('video', {
title : 'video按钮', //标题自拟
image : url+'/video.png', /图片放在主题js文件夹
onclick : function() {
ed.selection.setContent('');
}
});
},
createControl : function(n, cm) {
return null;
},
});
tinymce.PluginManager.add('video', tinymce.plugins.video);
})();

其他的js可以按此形式自己添加
当你完成以上步骤的时候 你就可以在可视化模式下看到你所创建的按钮了


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK