为了实现WordPress中的代码高亮显示插件,我们需要先为我们的主题文件添加所需的样式和JavaScript。让我们首先在主题的functions.php文件中添加以下CSS和JavaScript连接:

<?php
function custom_enqueue_scripts() {
if ( !is_admin() ) {
wp_enqueue_style( 'prism-stylesheet', 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.22.0/themes/prism.min.css', false, '1.22.0' );
wp_enqueue_script( 'prism-javascript', 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.22.0/prism.min.js', array(), '1.22.0', true );
wp_enqueue_script( 'prism-line-numbers', 'https://cdn.jsdelivr.net/npm/prismjs/plugins/line-numbers/prism-line-numbers.min.js', array(), '1.22.0', true );
}
}
add_action( 'wp_enqueue_scripts', 'custom_enqueue_scripts' );

这将添加Prism CSS和JavaScript文件以及行号插件(Line Numbers Plugin)。

接下来,我们将创建自定义短代码(Shortcode),用于在文章中指定高亮显示的代码段语言类型,以及识别并替换所有的高亮显示的HTML。

<?php
function custom_code_highlighter( $atts, $content = null ) {
extract( shortcode_atts( array(
'type' => '',
), $atts ));

if ( $type ) {
$code_start = ‘<pre><code class=”language-‘ . esc_attr( $type ) . ‘ line-numbers”>’;
} else {
$code_start = ‘<pre><code class=”language-none line-numbers”>’;
}

$code_content = $code_start . wp_kses_post( $content ) . ‘</code></pre>’;

return $code_content;
}
add_shortcode( ‘code’, ‘custom_code_highlighter’ );

现在,我们的主题和自定义短代码都已设定好。接下来,让我们将短代码添加到WordPress编辑器的快捷菜单中,以便用户更轻松地将其插入到文章内容中。

<?php
function custom_mce_buttons_2( $buttons ) {
array_push( $buttons, 'separator', 'highlighter' );
return $buttons;
}

function custom_mce_external_plugins( $plugins ) {
$plugins[‘highlighter’] = get_template_directory_uri() . ‘/js/custom-mce-button.js’;
return $plugins;
}

add_filter( ‘mce_buttons_2’, ‘custom_mce_buttons_2’ );
add_filter( ‘mce_external_plugins’, ‘custom_mce_external_plugins’ );

完成上述代码后,需要添加新的JavaScript文件来处理新的MCE按钮并替换所有的HTML代码。在主题的js文件夹内创建一个名为`custom-mce-button.js`的文件,输入以下代码:

javascript
(function() {
tinymce.PluginManager.add('highlighter', function( editor, url ) {
editor.addButton( 'highlighter', {
title: 'Add code highlighter',
icon: 'code',
onclick: function() {
editor.windowManager.open( {
title: 'Code Highlighter',
body: [{
type: 'listbox',
name: 'type',
label: 'Language type',
values: [
{ text: 'None', value: 'none' },
{ text: 'Bash', value: 'bash' },
{ text: 'CSS', value: 'css' },
{ text: 'HTML', value: 'html' },
{ text: 'JavaScript', value: 'javascript' },
{ text: 'PHP', value: 'php' },
{ text: 'Python', value: 'python' },
{ text: 'Ruby', value: 'ruby' },
{ text: 'SCSS', value: 'scss' }
]
},
{
type: 'textbox',
name: 'content',
label: 'Code snippet',
multiline: true,
minWidth: 600,
minHeight: 300,
value: ''
}],
onsubmit: function( e ) {
editor.insertContent( '[code type="' + e.data.type + '"]' + e.data.content + '[/code]' );
}
});
}
});
});
})();

现在,当用户编辑新的文章时,就可以通过快捷方式点击我们刚添加的按钮,在弹出框中设置代码高亮显示语言类型和内容。文章发表后,我们添加的自定义短代码会自动识别替换所有的高亮显示HTML。

希望这份完整的WordPress代码高亮显示插件的教程能够对您有所帮助!

发表回复

后才能评论