Adding highlighted blocks to wordpress 5+ posts

This has become so annoying I need to write it down in case I forget about it in the future (what’s the point of the HTML editor if the HTML gets modified by wordpress?).

When adding a piece of code you want to highlight with Syntax highlighter, best approach is:

  1. Click on the “+” of the block on the side, and search for “Custom HTML”, select it.
  2. Now you can add your “csharp” “js” or “html” tags as you wish with the already tabbed lines of code inside.
  3. If you click on preview that little block (there’s a button to do this) it won’t make it, but ignore, it actually works once you preview the entire post or publish it.

Some examples

Html (sourcecode language=”html”) or (html)

<h2>Here goes a bit of <span>html</span></h2>

Javascript (js)

function javascriptFunction(){
   // A comment
   var a = 0;
   console.log(a);
}

C# with a couple highlighted lines (csharp highlight=”3, 9″):

using (var httpClientHandler = new HttpClientHandler())
    {
        // Return `true` to allow certificates that are untrusted/invalid
        httpClientHandler.ServerCertificateCustomValidationCallback =
            HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

        using (var client = new HttpClient(httpClientHandler))
        {
            client.DefaultRequestHeaders.Add(headerKey, secret);

            var reqJson = JsonConvert.SerializeObject(request);
            var content = new StringContent(reqJson, Encoding.UTF8, "application/json");
            var response = await client.PostAsync(url, content);

            return response;
        }
    }

plain language (sourcecode language=”plain”)

plain code here

Warning

Looks like adding those tags to a simple paragraph will also trigger the Syntax Highlighter so be warn of what you add [between these].

Editing entire HTML

You can also go to options (the three dots) ยท> Code editor. But when you save/publish wordpress seems to review your post and edits it adding all sorts of p, br and pre tags up and down which will mess up your codes. The “Custom HTML” block seems a better approach.

Leave a Reply

Close Bitnami banner
Bitnami