Display highlighted code and unhighlighted formatted text on the same page(cocoon)

This article can be read in about 4 minutes.
PR

The purpose 

When code highlighting is enabled on a Cocoon page, formatted text other than code is also highlighted.

I don’t want the formatted text to be highlighted. On this site, I wanted to display the folder structure as formatted text, but the highlighting made it look strange.

ROOT
|   dice.glb
|   index.html
|
\---js
    +---libs
    |       3d.js
    |       GLTFLoader.js
    |       three.module.js
    |
    \---utils
            BufferGeometryUtils.js

like this.

PR

Changed in Cocoon settings

Highlight the source code

First, let’s configure syntax highlighting for your source code.

Go to “Cocoon Settings” in your WordPress admin panel, then click the “Code” tab. Check the box next to “Highlight source code” and click “Save Changes”.

With this setting, code will be highlighted, but formatted text and poetry outside of code blocks will also be highlighted.

Going a bit further, it seems all content within <pre> tags is being highlighted.

Narrow down the highlights

To solve the above problem, we’ll refine the highlighting target settings.

Following the same steps as above in the “Cocoon settings” -> “Code” tab, change the “CSS selectors to highlight” field at the bottom of the page as follows:

.entry-content pre.wp-block-code

MEMO(default)

.entry-content pre

Article writing

The settings are complete, so I’ll start writing the article.

When displaying code, please use code blocks

Use a formatted text block when displaying anything other than code.

Result

The blocks will be highlighted as follows

for (int i = 0 i < 10 ; i++)

The blocks will be highlighted as follows

for (int i = 0 i < 10 ; i++)

Unlike the code above, where background colors and other elements are highlighted, you can change this by styling the “wp-block-preformatted” class.

comment

Copied title and URL