WordPress主題實現代碼高亮顯示,一般都采用安裝插件的方式實現。大前端DUX主題嘗試N多插件,均無法令人滿意。繞了一大圈,個人感覺還是pre標簽好用,但是WordPress經典編輯器的文本裏缺少個代碼的快捷方式。網上搜索了一下,有很多不同的方法。篩選了一個,除了能增加自定義按鈕,還可以刪除原來的按鈕。代碼經過測試,適用于大前端DUX v6.0主題,不適用于大前端DUX v6.1主題。新版大前端DUX主題用戶直接將代碼添加到functions-theme.php文件中即可。
大前端DUX v6.0主題文件路徑:/wp-content/themes/dux/functions-theme.php
將下面的代碼添加到functions-theme.php文件的最後即可。
//veidc.com 添加HTML编辑器pre标签按钮 add_action('after_wp_tiny_mce', 'add_button_mce'); function add_button_mce($mce_settings) { ?> <script type="text/javascript"> QTags.addButton( 'eg_pre', 'pre', '<pre></pre>', '', 'q' ); //新增按钮 edButtons[120]=null; //删除按钮 </script> <?php }
注意:輸入<pre></pre>標簽需要在文本模式下進行(就是HTML標簽)。
而輸入代碼一定要在可視化模式下進行(幫您轉義)。
代碼解釋:
//新增按鈕行爲新增需要的按鈕。
//刪除按鈕行120爲所需的參數,具體參數可以查看當前WordPress版本的/wp-includes/js/quicktags.js
edButtons[10] = new qt.TagButton( 'strong', 'b', '<strong>', '</strong>', '', '', '', { ariaLabel: quicktagsL10n.strong, ariaLabelClose: quicktagsL10n.strongClose } ); edButtons[20] = new qt.TagButton( 'em', 'i', '<em>', '</em>', '', '', '', { ariaLabel: quicktagsL10n.em, ariaLabelClose: quicktagsL10n.emClose } ); edButtons[30] = new qt.LinkButton(); // special case edButtons[40] = new qt.TagButton( 'block', 'b-quote', '\n\n<blockquote>', '</blockquote>\n\n', '', '', '', { ariaLabel: quicktagsL10n.blockquote, ariaLabelClose: quicktagsL10n.blockquoteClose } ); edButtons[50] = new qt.TagButton( 'del', 'del', '<del datetime="' + _datetime + '">', '</del>', '', '', '', { ariaLabel: quicktagsL10n.del, ariaLabelClose: quicktagsL10n.delClose } ); edButtons[60] = new qt.TagButton( 'ins', 'ins', '<ins datetime="' + _datetime + '">', '</ins>', '', '', '', { ariaLabel: quicktagsL10n.ins, ariaLabelClose: quicktagsL10n.insClose } ); edButtons[70] = new qt.ImgButton(); // special case edButtons[80] = new qt.TagButton( 'ul', 'ul', '<ul>\n', '</ul>\n\n', '', '', '', { ariaLabel: quicktagsL10n.ul, ariaLabelClose: quicktagsL10n.ulClose } ); edButtons[90] = new qt.TagButton( 'ol', 'ol', '<ol>\n', '</ol>\n\n', '', '', '', { ariaLabel: quicktagsL10n.ol, ariaLabelClose: quicktagsL10n.olClose } ); edButtons[100] = new qt.TagButton( 'li', 'li', '\t<li>', '</li>\n', '', '', '', { ariaLabel: quicktagsL10n.li, ariaLabelClose: quicktagsL10n.liClose } ); edButtons[110] = new qt.TagButton( 'code', 'code', '<code>', '</code>', '', '', '', { ariaLabel: quicktagsL10n.code, ariaLabelClose: quicktagsL10n.codeClose } ); edButtons[120] = new qt.TagButton( 'more', 'more', '<!--more-->\n\n', '', '', '', '', { ariaLabel: quicktagsL10n.more } ); edButtons[140] = new qt.CloseButton();
上面展示的是WordPress v5.3.2 版本的具體參數,請您按照自己的需求刪除即可。