如何在WordPress可视化编辑器中添加插入短代码按钮?
在WordPress默认编辑器添加「添加短代码」按钮的实现方法
完全可以实现这个需求,直接把下面的代码加到主题的functions.php文件或者自定义插件里即可:
1. 注册编辑器按钮并加载交互脚本
add_action('admin_head', 'add_shortcode_button_to_editor'); function add_shortcode_button_to_editor() { // 仅在文章/页面编辑页面加载 if ( ! ( get_current_screen()->base === 'post' || get_current_screen()->base === 'page' ) ) { return; } ?> <script type="text/javascript"> jQuery(document).ready(function($) { tinymce.PluginManager.add('shortcode_button', function(editor) { // 添加工具栏按钮 editor.addButton('shortcode_button', { text: '添加短代码', icon: false, onclick: function() { // 获取WordPress中所有已注册的短代码 var shortcodes = <?php echo json_encode(array_keys(get_shortcode_tags())); ?>; // 构建短代码列表弹窗内容 var shortcodeList = '<div style="padding:15px;">'; shortcodeList += '<h3 style="margin-top:0;">选择要插入的短代码</h3>'; shortcodes.forEach(function(code) { shortcodeList += '<p><button class="insert-shortcode-btn" data-code="' + code + '" style="margin:4px;padding:6px 12px;cursor:pointer;">[' + code + ']</button></p>'; }); shortcodeList += '</div>'; // 打开弹窗 editor.windowManager.open({ title: '插入短代码', body: [{ type: 'container', html: shortcodeList }], width: 400, height: 'auto' }); // 绑定短代码插入事件 setTimeout(function() { $('.insert-shortcode-btn').on('click', function() { var code = $(this).data('code'); // 在光标位置插入短代码 editor.insertContent('[' + code + ']'); // 关闭弹窗 editor.windowManager.close(); }); }, 100); } }); }); }); </script> <?php } // 将按钮添加到编辑器工具栏 add_filter('mce_buttons', 'attach_shortcode_button_to_toolbar'); function attach_shortcode_button_to_toolbar($buttons) { // 把按钮放在「添加媒体」按钮的后面 $insertIndex = array_search('media', $buttons) + 1; array_splice($buttons, $insertIndex, 0, 'shortcode_button'); return $buttons; }
使用说明
- 代码生效后,编辑器工具栏会出现「添加短代码」按钮,点击后弹出所有已注册的短代码列表
- 点击对应短代码按钮,会自动在编辑器光标位置插入
[短代码名],之后你可以手动补充参数,比如改成[my_custom_code id="456" text="示例内容"] - 只要是通过
add_shortcode()注册的自定义短代码,都会自动出现在列表里
内容的提问来源于stack exchange,提问作者mwgideon
相关产品推荐
相关产品推荐

