Technology

Test post 001

Editando en un ordenador portátil

Reading time aprox: 5 minutes, 39 seconds

Hacking the WordPress editor or Improving the WordPress editor. In many cases, the internal WordPress editor is enough to perform the normal tasks in publishing your blog. But there are times when it falls, hmmmm, short. I mean, some of us use ways of highlighting certain words or groups of words. words, within the same paragraph.

[lwptoc]

What exists

The editor is designed so that a user can write content, without getting too involved in the layout, that is, in what is beautiful or appropriate to the aesthetics of the group. And for that purpose, it works quite well, both in the Visual writing format, and in HTML writing. But as fashions change, that editor is now known as «Classic Editor» and a new editor known by the code name «Gutenberg» or «Block Editor». Sometimes, however, the writer is also an editor and must worry about all aspects of writing, including its visual aspect, layout.

For example, a button

If you are using the classic editor and want to write a line like:

Hacking the editor is committed to offering all our readers the maximum readability, whatever their ability.

It seems easy, right? There is a word highlighted in a darker tone, “fatter” letters, what those who are used to layout call “bold.” That’s easy, the Visual editor has a button on its toolbar, as you see in this image.

Hackeando el editor - Aplicar formato de «negrita»
Hackeando el editor – Aplicar formato de «negrita»

Now comes the interesting thing, there are two words that appear in red (maximum readability), which is how the creators of the corporate identity have decided that the important words should appear. No matter how hard you try, there is no button in the editor that allows you to color one or more words red. Oops! It is not true, if there is a button that allows you to color the text, it is called text color, as seen in the image.

Hackeando el editor - Color del Texto
Hackeando el editor – Color del Texto

But… What would happen if the creators of the corporate identity decided that the highlighted words should be in a different font and a different color and a different size?

Hacking the editor.

Well, it turns out that it is no longer so simple, the type of font is defined for a type of block and the minimum block that the editor considers is the paragraph. If you want to make a change in the middle of a paragraph, you have to use the HTML editor and define the rules yourself. If you know a little about layout, you will know that this insertion is done using the <span></span> tag, and within that tag, the class=. That is, you should put, for example: <span class=”highlighted”>maximum readability</span> and then, you have to complement that with the style in the Theme style sheet, where the developers have defined the style. For example:

.resaltado {
color: rgb(255, 113, 57);
font-weight: bold;
font-family: monospace;
font-size: 1.5rem;
}

And yes, you are ready, if you write the paragraph:

By hacking the editor, you are committed to offering <strong>everyone</strong> our readers, the <span class=”highlighted”>maximum readability</span>, whatever their ability.

Your blog reader will see:

Hacking the editor is committed to offering all our readers the maximum readability, whatever its capacity.

Well, if this is your case, I am going to tell you how you can create a new button for the classic editor, so that you can apply the desired style to a section of the paragraph.

How does it work?

The editor in WordPress (remember, I’m talking about the Classic Editor) is quite simple in its operation and bases its operation on two basic parts, the visual presentation part of the content and the text entry part. I make this differentiation to visualize the two environments, the local one (on the server) of representation of the database content and the remote one (on the user’s device) that collects the text and sends it to the server so that it becomes the content of the database. This is explained in broad strokes and surely some of you will be able to say: it is not true, it is not like that…! but I beg you to allow me this “license” so that we can all understand each other. Continuing with this separation, we have two points of action:

  1. The local part, the functions.php file of your Theme (preferably, your Child Theme).
  2. The remote part, a JavaScript program, which interacts with the server, so that the editor offers you an option that it does not normally offer you.

¡Empezamos!

Hacking the editor.

On the server

For the editor to work, we have to tell WordPress to make a small change and apply a modification to its behavior. The code that we must insert in the file functions.php is:

/* ************************************ */
/* add custom button in mce editor */
function slwp_add_mce_button() {
if ( !current_user_can( 'edit_posts' ) && !current_user_can( 'edit_pages' ) ) {
return;
  }
if ( 'true' == get_user_option( 'rich_editing' ) ) {
add_filter( 'mce_external_plugins', 'slwp_add_tinymce_plugin' );
add_filter( 'mce_buttons', 'slwp_register_mce_button' );
  }
}
add_action('admin_head', 'slwp_add_mce_button');

function slwp_add_tinymce_plugin( $plugin_array ) {
$plugin_array['style_select'] = get_stylesheet_directory_uri() .'/js/tiny_estilos.js';
return $plugin_array;
}

function slwp_register_mce_button( $buttons ) {
array_push( $buttons, 'style_select' );
return $buttons;
}

These three functions perform the tasks of:

slwp_add_mce_button()
Checks if the user has editing authority and, if so, invokes the other functions.
slwp_add_tinymce_plugin( $plugin_array )
Defines the button in the editor which, in this case, is a selection field whose values ​​are defined in the JavaScript program file
slwp_register_mce_button( $buttons )
Create the button in the editor, inserting an array with the button definition.

Hacking the editor.

On the remote device

I am referring to the remote device, because it can be a PC, a Tablet, or a Smartphone. The only thing you need is that you have an Internet browser that understands the JavaScript language (and is able to use it 😜). Of course, we do not have access to that device, and we cannot install an application on it, but we can send it a file with the JavaScript code that it has to execute. To do this, we store the file with the code on the server and send it to any device that is trying to perform editing tasks. Remember that in the slwp_add_tinymce_plugin() function, we tell WordPress what file we want it to send, in this case: tiny_estilos.js , which is hosted in the “js” directory of the Theme directory. The content of the file tiny_estilos.js is:

/* insertar desplegable en tiny_mce */
(function() {
var styles = ['highlighted', 'highlighted1', 'highlighted2', 'bold', 'italic'];
  
tinymce.PluginManager.add( 'style_select', function( editor ){
    
var items = [];

tinymce.each( estilos, function( styleName ){
items.push({
text: styleName,
onclick: function(){
var content = tinyMCE.activeEditor.selection.getContent();
editor.insertContent( '' + content + '' );
        }
      });
    });

editor.addButton( 'style_select', {
type: 'menubutton',
text: 'Style',
menu: items
    });

  });
})();

This small program instructs the Tiny_MCE editor, the «Classic Editor» of WordPress, to include among its options, a drop-down list with the style options we need.

Hacking the editor - Classes button added
Hacking the editor – Classes button added

In this specific case, the options are those included in the “styles” matrix and are: ‘highlighted’, ‘highlighted1’, ‘highlighted2’, ‘bold’, ‘italic’. Now it depends on how each of those styles are defined, in the corresponding style.css file of the Theme in use. For example as said above, to define the style first:

...
.highlighted {
color: rgb(255, 113, 57);
font-weight: bold;
font-family: monospace;
font-size: 1.5rem;
}
...

Hacking the editor.

Trick

One of the biggest drawbacks of the Visual editing mode is that it is not possible to appreciate changes in font, color, or other characteristics, except for basic functions such as bold or italics. In order to see the styles that have been designed and applied to the paragraphs, you must save what you have written as a draft and click on the link that appears at the beginning of the entry: «Draft entry updated. Entry preview». But there is a way to “trick” the editor, so that it represents (in its “Visual” form) the styles that we want to define. This involves creating a file with the name custom-editor-style.css. This file contains the style sheet with the definitions that we want the editor to use. These styles can contain the definition of how we want to see the “h” headings or the definition of “highlighting”, among others. For it to work, you have to upload the style file to the server, in the same Theme directory (next to the other style sheet “style.css” 😉).

The Block editor

Everything we have said so far about the separation of functions and environments is true in any case, but the Block Editor has a different behavior from the Classic Editor, so it requires a different treatment.

En el server

The functions that we must insert in the file functions.php are:

function slwp_span_guten(){
wp_enqueue_script(
'span_guten',
plugins_url('span_guten.js'),
array('wp-blocks', 'wp-i18n', 'wp-element', 'wp-components', 'wp-editor'),
'1.0', true
//filemtime(plugin_dir_path( __FILE__ ).'span_guten.js')
    );
}
add_action('enqueue_block_editor_assets', 'span_guten');

While the necessary JavaScript file contains:

const { createElement, Fragment } = window.wp.element
const { registerFormatType, toggleFormat } = window.wp.richText
const { RichTextToolbarButton, RichTextShortcut } = window.wp.editor;
[
  {
name: 'highlighted',
title: 'Highlight',
lang: 'class',
icon: 'format-chat',
  },
  {
name: 'highlight1',
title: 'Highlight1',
lang: 'class',
icon: 'format-chat',
  },
   {
name: 'highlight2',
title: 'Remarked2',
lang: 'class',
icon: 'format-chat',
  },
   {
name: 'centered',
title: 'Centered',
lang: 'class',
icon: 'format-chat',
  },
   {
name: 'italica',
title: 'Italica',
lang: 'class',
icon: 'format-chat',
  }
].forEach( ({ name, title, lang, icon} ) => {
const type = "advanced/${name}" registerFormatType(type, { title, tagName: 'span', className: lang, edit ({ isActive, value, onChange }) { const onToggle = () => onChange(toggleFormat(value, { type })) return ( createElement(Fragment, null, createElement(RichTextToolbarButton, { title, icon: icon, onClick: onToggle, isActive, className: "toolbar-button-with-text toolbar-button__advanced-${name}" }) ) ) } }) })

And as in the case of the Classic Editor, your style sheet should contain the style definitions that you have included, such as:

...
.highlighted {
color: rgb(255, 113, 57);
font-weight: bold;
font-family: monospace;
font-size: 1.5rem;
}
...

Hacking the editor.

Conclusion

Now that it is fashionable to use the anglicism of Hacking (incorrect, on the other hand) to say “Improve” or “Alter”, we will not be less and, on the other hand, it is always good to acquire new knowledge. 😜 Remember that you can also expand the editor’s capabilities by installing one of the plugins you find in the official WordPress repository. In the meantime, remember, #WearMask, #WashHands, play, experiment and, above all, have fun!


Thank you for reading this article! Please "like it" and comment!

Tagged ,

Leave a Reply

Your email address will not be published. Required fields are marked *