在努力添加后pre
元素,我决定在TinyMCE编辑器上创建一个快捷按钮:
这是我的父主题中的按钮类和挂钩:
/**
* EmbedSourceCodeButton
*
* @see https://codex.wordpress.org/TinyMCE_Custom_Buttons
*/
final class EmbedSourceCodeButton
{
/**
* Name
*/
const NAME = \'embedSourceCodeButton\';
/**
* Constructor
*/
function init()
{
if (\'post\' !== $GLOBALS[\'current_screen\']->post_type) return;
add_action(\'mce_buttons\', [$this, \'addButton\']);
add_action(\'mce_external_plugins\', [$this, \'addPlugin\']);
add_action(\'admin_enqueue_scripts\', [$this, \'localizeLabels\'], 10, 0);
}
/**
* Localize labels
*/
function localizeLabels()
{
wp_localize_script(\'jquery-core\', self::NAME, [
\'title\' => __(\'Embed Source Code\', \'textdomain\'),
\'listboxLabel\' => __(\'Language\', \'textdomain\'),
\'textboxLabel\' => __(\'Source code\', \'textdomain\')
]);
}
/**
* Add this button to TinyMCE
*
* @see https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/class-wp-editor.php#L624
*
* @return array $buttons
*/
function addButton(array $buttons)
{
array_push($buttons, self::NAME);
return $buttons;
}
/**
* Add this plugin
*
* @see https://core.trac.wordpress.org/browser/tags/4.6/src/wp-includes/class-wp-editor.php#L392
*
* @return array $plugins
*/
function addPlugin(array $plugins)
{
$x = SCRIPT_DEBUG ? \'\' : \'.min\';
if ( !isset($plugins[self::NAME]) )
$plugins[self::NAME] = get_template_directory_uri() . \'/assets/js/button\' . $x . \'.js\';
return $plugins;
}
}
add_action(\'load-post.php\', [new EmbedSourceCodeButton, \'init\']);
add_action(\'load-post-new.php\', [new EmbedSourceCodeButton, \'init\']);
这是
button.js
在里面
asset/js
我的主题文件夹:
(function() {
tinymce.PluginManager.add(\'embedSourceCodeButton\', function(editor, url) {
editor.addButton(\'embedSourceCodeButton\', {
text: false,
icon: \'wp_code\',
onclick: function() {
editor.windowManager.open({
title: embedSourceCodeButton.title,
body: [
{ // Unnecessary yet but may be helpful in the future.
name: \'language\',
type: \'listbox\',
label: embedSourceCodeButton.listboxLabel,
values: [
{
text: \'PHP\',
value: \'php\'
},
{
text: \'CSS\',
value: \'css\'
},
{
text: \'HTML\',
value: \'html\'
},
{
text: \'Javascript\',
value: \'javascript\'
}
]
},
{
name: \'code_block\',
type: \'textbox\',
multiline: true,
label: embedSourceCodeButton.textboxLabel
}
],
onsubmit: function(e) {
e.stopPropagation();
var entities = {
\'&\': \'&\',
\'<\': \'<\',
">": \'>\',
\'"\': \'"\',
"\'": \''\',
\'/\': \'/\'
};
// Encode HTML special chars before inserting into editor.
var codeBlock = e.data.code_block.replace(/&|<|>|"|\'|\\//gm, function(s) {
return entities[s];
});
editor.insertContent(\'<pre data-lang="\' + e.data.language + \'"><code>\' + codeBlock + \'</code></pre>\');
}
});
}
});
});
})();
希望它能帮助像我这样懒惰的人