WordPress富文本编辑器添加Pre自定义按钮

  • 2023-06-20 20:56:12
  • 692 次阅读
  • 稿源:天马行空

要在WordPress编辑器中添加自定义的按钮,可以按照以下步骤进行操作:

打开主题的functions.php文件。在文件中添加以下代码:

function star_add_custom_pre_button() {
    if (current_user_can('edit_posts') && current_user_can('edit_pages')) {
        add_filter('mce_buttons', 'register_custom_pre_button');
        add_filter('mce_external_plugins', 'add_custom_pre_plugin');
    }
}
function register_custom_pre_button($buttons) {
    array_push($buttons, 'custom_pre');
    return $buttons;
}
 
function add_custom_pre_plugin($plugins) {
    $plugins['custom_pre'] = get_template_directory_uri() . '/assets/js/custom-pre-plugin.js';
    return $plugins;
}
add_action('admin_init', 'star_add_custom_pre_button');

在主题目录中创建一个名为js的文件夹。

在js文件夹中创建一个名为custom-pre-plugin.js的文件。

在 custom-pre-plugin.js 文件中,添加以下代码:

(function() {
    tinymce.PluginManager.add('custom_pre', function(editor, url) {
        editor.addButton('custom_pre', {
            text: 'Pre',
            icon: false,
            onclick: function() {
                editor.execCommand('mceInsertContent', false, 'Your code here');
            }
        });
    });
})();

保存文件并将它们上传到主题文件夹中。

现在,当你在编辑器中创建或编辑文章时,应该会看到一个名为”Pre”的按钮。当选中代码并点击该按钮时,它将插pre标签并将选中的内容放在标签内。

请确保在编辑器页面上刷新或重新加载页面后,你才能看到新添加的按钮。

喜欢 1

文章评论 (0)

表情

大眼 可爱 大笑 坏笑 害羞 发怒 折磨 快哭了 大哭 白眼 晕 流汗 困 腼腆 惊讶 憨笑 色 得意 骷髅 囧 睡觉 眨眼 亲亲 疑问 闭嘴 难过 淡定 抗议 鄙视 猪头