如何给wordpress的编辑器添加一个自定义按钮,并且实现插入功能

1、添加按钮

在  functions.php  文件里面添加下面代码:

add_action('media_buttons', 'add_my_media_button');

function add_my_media_button() {
 echo '<a href="#" id="insert-my-media" class="button">Add my media</a>';
 }

添加后,登录后台编辑文章看到如图所示:

2、添加命令

继续添加代码,引用自己定义的JS,我命名为  media_button.js  。

function my_enqueue( $hook_suffix ) {
 if ( 'post-new.php' == $hook_suffix ) {
 wp_enqueue_script('media_button', '/wp-content/themes/netnote/js/media_button.js', array('jquery'), '1.0', true);
 } 
}

3、添加JS命令

media_button.js 添加下面代码:

jQuery(function($) {
 jQuery(document).ready(function(){
 jQuery('#insert-my-media').click(open_media_window);
 });
 
 function open_media_window() {
 if (this.window === undefined) {
 this.window = wp.media({
 title: 'Insert a media',
 library: {type: 'image'},
 multiple: false,
 button: {text: 'Insert'}
 });
 
 var self = this; // Needed to retrieve our variable in the anonymous function below
 this.window.on('select', function() {
 var first = self.window.state().get('selection').first().toJSON();
 wp.media.editor.insert('[myshortcode id="' + first.id + '"]');
 });
 }
 
 this.window.open();
 return false;
 }
});

就可以实现点击按钮弹出媒体选择框,插入之后自动插入短网址。