当前位置:

让你的 Bricks 网站像大厂一样展示代码:深度定制 Prism.js 高亮指南

简介:WordPress 默认的代码块太丑?本指南教你如何在 Bricks Theme 中深度集成 Prism.js,实现带行号、一键复制、自动语言标签的专业代码展示效果,提升技术博客的专业感。

为什么你的技术博客需要专业的高亮方案?

作为一名网站运营者,我们知道细节决定留存。如果你在分享技术教程或代码片段,古腾堡编辑器默认那种灰扑扑、排版混乱的代码块会极大降低读者的阅读欲望。一个专业、美观的代码块不仅能提高可读性,还能通过“一键复制”等交互功能提升用户体验(UX)。

今天,我们就基于强大的 Bricks Theme,手把手教你搭建一套“大厂级别”的代码高亮系统。

核心功能亮点

  1. 极速加载:不依赖外部 CDN,资源完全托管在你的子主题中,秒开不卡顿。
  2. 视觉盛宴:采用经典的 Tomorrow Night 配色,配合 12px 圆角和悬浮阴影,质感拉满。
  3. 智能交互
    • 自动识别:无需手动设置,脚本自动识别 PHP、HTML、CSS 等语言。
    • 一键复制:内置汉化反馈,点击即显 √已复制
    • 行号对齐:精准的行号显示,方便读者快速定位。
  4. 完美的圆角:通过 CSS 容器裁剪技术,彻底解决了工具栏与代码块交界处的“尖角”难题。

实现思路简述

我们放弃了沉重的插件,转而使用轻量级的 Prism.js(在https://prismjs.com/download.html中下载对应的主题、代码、功能,然后在古腾堡中额外css填入code-php/code-sql等方式)。通过在 Bricks 子主题的 functions.php 中注入一小段“魔法”代码:

/**
 * ============================================================
 * 【功能增强版】WordPress + Bricks 代码高亮 (Feature 1)
 * ============================================================
 * 支持在后台给代码块添加 Additional CSS Class: code-sql, code-php 等
 */

// 1. 加载本地子主题资源 (assets/prism/ 目录下)
add_action('wp_enqueue_scripts', function() {
    if (is_singular('post')) {
        $uri = get_stylesheet_directory_uri() . '/assets/prism';
        wp_enqueue_style('prism-local-style', $uri . '/prism.css', array(), '1.29.0');
        wp_enqueue_script('prism-local-script', $uri . '/prism.js', array(), '1.29.0', true);
    }
}, 20);

// 2. 注入初始化脚本与视觉 UI 美化
add_action('wp_footer', function() {
    if (!is_singular('post')) return;
    ?>
    <script id="bricks-prism-universal-fix">
    (function() {
        const setupPrism = () => {
            const preBlocks = document.querySelectorAll('pre');
            if (preBlocks.length === 0) return;

            preBlocks.forEach(pre => {
                const code = pre.querySelector('code');
                if (code) {
                    // --- A. 核心:识别自定义 code-xxx 风格的类名 (用于手动设置语言) ---
                    // 检查 pre 标签是否有 code-xxx 类 (例如 code-sql, code-css)
                    const customLangMatch = pre.className.match(/code-(\w+)/);
                    if (customLangMatch) {
                        const lang = customLangMatch[1];
                        code.classList.add(`language-${lang}`);
                        pre.classList.add(`language-${lang}`);
                    }

                    // --- B. 基础:补全 Prism 必需的类名 ---
                    const currentLangMatch = code.className.match(/language-(\w+)/);
                    if (currentLangMatch) {
                        const fullLangClass = currentLangMatch[0];
                        // 同步类名至 pre 标签 (Prism 插件需要)
                        if (!pre.className.includes(fullLangClass)) pre.classList.add(fullLangClass);
                    } else {
                        // 如果没有识别到任何语言,默认回退到 PHP
                        code.classList.add('language-php');
                        pre.classList.add('language-php');
                    }

                    // 启用行号和括号匹配
                    pre.classList.add('line-numbers');
                    pre.classList.add('match-braces');
                }
            });

            if (window.Prism) {
                Prism.highlightAll();
                
                // --- 核心:手动接管点击反馈逻辑,实现 √已复制 ---
                const handleCopyFeedback = () => {
                    document.querySelectorAll('.copy-to-clipboard-button').forEach(btn => {
                        // 1. 初始汉化按钮文字
                        if (btn.innerText.toLowerCase().includes('copy') || btn.innerText === '') {
                            btn.innerText = '复制';
                        }

                        // 2. 绑定点击事件,确保点击瞬间有 √ 符号提示
                        if (!btn.dataset.observed) {
                            btn.addEventListener('click', function() {
                                btn.innerText = '√已复制';
                                btn.style.color = '#8cc2ff'; 
                                setTimeout(() => {
                                    btn.innerText = '复制';
                                    btn.style.color = '#fff';
                                }, 2000);
                            });
                            btn.dataset.observed = "true";
                        }
                    });
                };
                setTimeout(handleCopyFeedback, 500);
                setTimeout(handleCopyFeedback, 1500);
            }
        };
        window.addEventListener('load', setupPrism);
        setTimeout(setupPrism, 1000);
    })();
    </script>

    <style>
        /* --- 1. 最外层容器:控制圆角 (12px) 和溢出裁剪 --- */
        .code-toolbar {
            position: relative !important;
            margin: 2.5em 0 !important;
            border-radius: 12px !important; 
            overflow: hidden !important; 
            background-color: #1d1f21 !important;
            box-shadow: 0 10px 30px rgba(0,0,0,0.4);
        }

        /* --- 2. 顶部工具栏:确保高度和背景贴合圆角 --- */
        .code-toolbar .toolbar {
            position: absolute !important;
            top: 0 !important;
            left: 0 !important;
            width: 100% !important;
            height: 46px !important; 
            opacity: 1 !important; 
            visibility: visible !important;
            display: flex !important;
            align-items: center;
            justify-content: space-between;
            padding: 0 15px;
            background: rgba(0, 0, 0, 0.4) !important;
            border-bottom: 1px solid rgba(255, 255, 255, 0.08);
            box-sizing: border-box;
            z-index: 10;
        }

        /* 左侧语言标签 (SQL, PHP 等) */
        .toolbar-item > span { 
            display: inline-block !important;
            color: #8cc2ff !important; 
            font-size: 11px !important; 
            font-weight: 700 !important;
            text-transform: uppercase;
            padding: 4px 12px !important;
            background: rgba(140, 194, 255, 0.1) !important;
            border: 1px solid rgba(140, 194, 255, 0.2) !important;
            border-radius: 6px !important;
            letter-spacing: 0.5px;
        }

        /* 右侧复制按钮 */
        .code-toolbar .toolbar-item button {
            background: #444 !important;
            color: #fff !important;
            border: 1px solid #555 !important;
            border-radius: 6px !important;
            padding: 5px 14px !important; 
            font-size: 11px !important;
            font-weight: 600 !important;
            cursor: pointer;
            transition: all 0.2s ease;
            outline: none !important;
        }
        .code-toolbar .toolbar-item button:hover { background: #555 !important; }

        /* --- 3. 代码容器:缩减上下间距 --- */
        pre[class*="language-"] {
            margin: 0 !important;
            padding: 48px 0 8px 0 !important; 
            background: transparent !important;
            border-radius: 0 !important; 
            height: auto !important;
            max-height: none !important;
            overflow: visible !important; 
        }

        /* --- 4. 代码文字:缩减上下 Padding --- */
        pre[class*="language-"].line-numbers code {
            display: block !important;
            padding: 10px 1.5em 10px 4.5em !important; 
            margin: 0 !important;
            white-space: pre !important;
            color: #c5c8c6 !important;
            font-family: 'Fira Code', 'Consolas', monospace !important;
            font-size: 14px !important;
            line-height: 1.85 !important;
            text-shadow: none !important;
        }

        /* --- 5. 行号同步 --- */
        .line-numbers .line-numbers-rows {
            position: absolute !important;
            top: 10px !important; 
            left: 0 !important;
            width: 3.5em !important; 
            height: calc(100% - 20px) !important;
            border-right: 1px solid rgba(255, 255, 255, 0.1) !important;
            background: transparent !important;
        }
        .line-numbers-rows > span:before {
            color: #5c6370 !important;
            text-align: right;
            padding-right: 12px;
        }
    </style>
    <?php
}, 100);
  • 后端脚本:强制在文章单页加载必要的 CSS 和 JS。
  • 前端逻辑:动态修补古腾堡生成的 HTML 结构,自动注入语言标签和工具栏。
  • 自定义样式:通过 !important 级 CSS 覆盖,确保不受主题默认样式的干扰,解决常见的行距重叠和滚动条问题。

结语

一个优秀的技术网站,代码块的颜值就是它的门面。通过这套针对 Bricks Theme 深度优化的方案,你不仅能获得媲美 GitHub 的展示效果,更能保持网站的轻量与高效。

分享到:

留下第一个评论

品牌出海,即刻开启

点击咨询