wordpress经典编辑器插入短代码高亮

使用方法

1.找到主题functions.php文件粘贴以下代码保存刷新

进入后台编写文章编辑器有个插入高亮代码块

// 后台编辑器添加下拉式按钮 - 代码高亮版
function QGG_select(){
    echo '
    ';
}
if (current_user_can('edit_posts') && current_user_can('edit_pages')) {
add_action('media_buttons', 'QGG_select', 11);
}
function QGG_button() {
echo '';
}
add_action('admin_head', 'QGG_button');
/**
* 代码高亮 + 一键复制(经典编辑器友好)- 本地化优化版
* 使用方法:在文章"文本模式"中用
...
包裹代码
*/
// 1. 加载 Highlight.js 样式和脚本(本地化)
function enqueue_highlight_js() {
if (is_single() || is_page()) {
wp_enqueue_style(
'highlight-style',
THEME_URL . '/inc/assets/css/highlight-atom-one-dark.min.css',
[],
'11.9.0'
);
wp_enqueue_script(
'highlight-js',
THEME_URL . '/inc/assets/js/highlight-common.min.js',
[],
'11.9.0',
true
);
}
}
add_action('wp_enqueue_scripts', 'enqueue_highlight_js');
// 2.5. 添加代码块样式(保持格式)
function add_code_block_styles() {
if (is_single() || is_page()) {
wp_add_inline_style('highlight-style', '
pre {
white-space: pre !important;
overflow-x: auto !important;
word-wrap: normal !important;
}
pre code {
white-space: pre !important;
word-break: normal !important;
word-wrap: normal !important;
overflow-wrap: normal !important;
display: block !important;
line-height: 1.6 !important;
}
/* 防止空行被折叠 */
pre code br {
display: none !important;
}
');
}
}
add_action('wp_enqueue_scripts', 'add_code_block_styles');
// 2. 初始化高亮 + 添加复制按钮
function add_highlight_and_copy_button() {
if (is_single() || is_page()) {
?>
]*>.*?<\/pre>/is', function($matches) { global $code_block_placeholders; $placeholder = ''; $code_block_placeholders[$placeholder] = $matches[0]; return $placeholder; }, $content ); return $content; } function restore_code_blocks_after_wpautop($content) { global $code_block_placeholders; if (empty($code_block_placeholders)) { return $content; } // 恢复代码块 foreach ($code_block_placeholders as $placeholder => $code_block) { $content = str_replace($placeholder, $code_block, $content); } // 清理全局变量 $code_block_placeholders = array(); return $content; } // 在wpautop之前保护代码块(优先级1,非常早) add_filter('the_content', 'protect_code_blocks_from_wpautop', 1); // 在wpautop之后恢复代码块(优先级999,最晚) add_filter('the_content', 'restore_code_blocks_after_wpautop', 999);

消息盒子
# 您需要首次评论以获取消息 #
# 您需要首次评论以获取消息 #

只显示最新10条未读和已读信息