在 WordPress 经典编辑器中将 H1-H5 标题格式以独立按钮形式直接显示(非下拉菜单)
添加到主题的 functions.php
// 添加标题按钮到第一行工具栏
function custom_add_heading_buttons($buttons) {
array_splice($buttons, 5, 0, array('h1_button', 'h2_button', 'h3_button', 'h4_button', 'h5_button'));
return $buttons;
}
add_filter('mce_buttons', 'custom_add_heading_buttons');
// 注册按钮功能
function custom_register_buttons($plugin_array) {
$plugin_array['customheadings'] = get_theme_file_uri('/js/custom-heading-buttons.js');
return $plugin_array;
}
add_filter('mce_external_plugins', 'custom_register_buttons');
创建js文件,文件路径:主题目录/js/custom-heading-buttons.js
(function() {
tinymce.PluginManager.add('customheadings', function(editor, url) {
editor.addButton('h1_button', {
title: '标题 1',
icon: false,
text: 'H1',
onclick: function() { editor.formatter.toggle('h1'); }
});
editor.addButton('h2_button', {
title: '标题 2',
icon: false,
text: 'H2',
onclick: function() { editor.formatter.toggle('h2'); }
});
editor.addButton('h3_button', {
title: '标题 3',
icon: false,
text: 'H3',
onclick: function() { editor.formatter.toggle('h3'); }
});
editor.addButton('h4_button', {
title: '标题 4',
icon: false,
text: 'H4',
onclick: function() { editor.formatter.toggle('h4'); }
});
editor.addButton('h5_button', {
title: '标题 5',
icon: false,
text: 'H5',
onclick: function() { editor.formatter.toggle('h5'); }
});
});
})();
实现效果:
编辑器第一行工具栏会显示 H1 H2 H3 H4 H5 五个文本按钮
选中文字后点击对应按钮即可切换标题格式
按钮状态会自动同步当前光标所在段落的标题级别

优点说明:
直观操作 - 所有标题按钮直接可见,无需展开二级菜单
状态反馈 - 当光标处于标题中时,对应按钮会自动高亮
兼容性强 - 不会与默认的格式下拉菜单产生冲突
响应快速 - 纯JS实现,无Ajax请求延迟
注意事项:
需要确保主题目录下存在 /js/custom-heading-buttons.js 文件
如果工具栏空间不足,可将按钮移动到第二行(修改 mce_buttons 为 mce_buttons_2)
按钮文字 H1-H5 可根据需求修改为图标(需使用 icon: 'icon-class' 并加载对应字体图标)
Fonts downloaded from the "Free Fonts" column can be used commercially without purchasing copyrights. They are carefully verified by multiple parties before being released. However, it cannot be ruled out that the copyright holder or font author modifies the license one day, or that there are inadvertent omissions in the verification process. Therefore, in actual commercial use, it is recommended to contact the copyright holder or font author for further verification.
The fonts are from the Internet or personal contributions. They are only for personal non-commercial download. Please do not use them for commercial purposes. If you use them for commercial purposes, please contact the font author or the font copyright owner. If there is any infringement, please contact us to disconnect the link.Email:fontsvip@gmail.com
Although we have indicated the license type, please make sure to double check it by reading the information shown in the details area of each font to avoid any confusion. If you are not sure, do not hesitate to contact the font author.
