After struggling about adding pre
element manually, I decided to create a shortcut button on TinyMCE Editor:
This is button class and hooks in my parent theme:
/**
* 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']);
And this is button.js
which is inside asset/js
folder of my theme:
(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>');
}
});
}
});
});
})();
Hope it can help someone who is lazy as me too. ;-)
<pre></pre>
around the code?<pre></pre>
manually. Isn't it's equal topreformatted
button or I have missed something?pre
element each time.