How to display[C,C++,JAVA] Code in blogpost

Have you ever excited to write a code in a blog post, but I was excited when I started  the blogging

Here are four different ways to write a code in blogpost

  1. Default editor
  2. WordPress Plugin
  3. Embed code snippet
  4. Use a syntax highlighter library[highlight.js]

We can write code in WordPress blogpost by using default editor and this is the simplest and the easiest way to do

  1. Go to your WordPress dashboard
  2. Create a new post
  3. Click on the ADD block (+) symbol
  4. Write in search box “code” then
  5. Select formatting <> code option
  6. Copy and paste your code in the write code box

Let us see one code example, how it looks like in blogpost by using the default editor

Addition of number of elements in an array with C

 code Default editor wordpress

The dumb thing about using a Default editor

Here is the first problem

the code you inserted into a default editor will not get highlighted with any color

Guess what!

The code will look simple and plain without any highlight

That’s okay!

Here’s another one

the code which is inserted into the default editor will not fit the computer or mobile screen and you need to slide the code on the right side with a slider to view the complete code

it will crush the spirit of effortless scanning of the page

But, you can change the background color and text color of the code.

Oh, by the way, when you add background color to the code then at that instant, you might find extra padding around the code block

now, to fix this problem, add below code snippet to the <head> tag of your site.

<style>pre {padding: 0px;}</style>

Yet, the best way to display code with WordPress is the default way

Why?

Because the default way will not add extra weight to the page

But why should I care about page weight?

Because a higher page weight means a higher load time for your site

Here is my advice, always maintain your site weight as minimum as possible so that your site loads faster  

Instead of using a default editor, you can use a plugin to display code

But here, I would like to share my experiences with plugins rather than how to use them

Here are plugins that I used to use

(i)Crayon syntax highlighter [the plugin stopped functioning]

(ii) SyntaxHighlighter Evolved

However, do you think these syntax highlighter plugins are infallible and work with no hassle throughout the lifetime

No! friend That’s not true

In the journey of your WordPress site, these syntax highlighter plugins can paralyze you at one point

Why do you say that?

Because these syntax highlighting plugins are not high-quality plugins

Meanwhile, if you have built your site using a syntax highlighter  plugin  and have written a huge amount of code with it

now, guess what!

 The plugin stopped working.

at this point you need to change the whole website code which is painful furthermore, you will waste huge chunk of time

Here is how your code will be wrapped in pre-tag rather than code

<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""> here is your code</pre>

let’s deconstruct an example

let me tell you about an incident,  3years back I was using a plugin called enlighter-customizable syntax highlighter

as time passed, I started more code with the plugin on the site

guess what happened?

Of course, the plugin stopped

Thus, this incident put me in a gloomy mood

why?

because the site got out of order and it took time and effort to get back in order

Do you know? how to embed code snippets in a blog post? and This is a third way of displaying code in WordPress

We have seen how posts code displayed in WordPress by default editor also using WordPress plugin let us see how to display WordPress code snippet by embed method

In order to display WordPress code, we use an online tool called GitHub gist

Step 1

  1. Log in to your GitHub account
  2. Go to GitHub Gist
  3. Write a file for the code
  4. Copy and paste your code in Gist

Step 2

  1. Copy the embed code script
  2. And paste in the paragraph of your blog with the edit as Html and
  3. publish
posts code

let us see how the syntax of the code will look like when we use GitHub Gist to display WordPress code snippets  

But, here’s the problem with embedding code snippets with GitHub gist. It creates pagespeed insight issues

First issue: creates a render-blocking resources

Second issue: create 2 links with add the document.write()

You don’t need to be a developer  to install and use highlight.js library so, don’t panic

Okay,

I can guarantee you that it would be a lot simpler than you think

Of course, installing a library in WordPress is usually done by a developer but to install highlight.js library you don’t have to write any scary code

Let’s dive in

Well, there are different ways to install a library in WordPress

 but here are the two basic methods

  1. Install it through a plugin
  2. By editing the theme file editor
Install it through a plugin

First, install a plugin called wpcode

Next, You need to copy and paste the Three tags into your plugin header section and click Save changes

but wait! Where to find these Three tags

You can get these Three tags of the library from here the highlight.js library

Here you might find four tags

But you need only these three tags

That’s it! We have installed the highlight.js library on WordPress

Now, verify the setup.

  1. Go to your WordPress dashboard
  2. Create a new post
  3. Click on the ADD block (+) symbol
  4. Write in search box “code” then
  5. Select formatting <> code option
  6. Copy and paste your code in the write code box

Here, no need to mention the language

Why?

Because highlight.js will detect it automatically

But, if you mentioned the language the highlight will be effective

Here is how you can mention the name of the language

<pre><code class="language-html">...</code></pre>

Here are the aliases of languages that are listed on this site

But, how do I choose a theme?

Well, if you are installing a highlight.js through the cdnjs method then you need to replace the path_to/default.min.css with path_to/my_specific_theme_name.css

Thats it!

Instead of cdnjs method, if you are self-hosting highlight.js then you need to find my_theme.css file in the styles folder of the downloaded .zip folder and upload it to your server

Do you want to travel even further down there?

But why should I? I installed the highlight.js library

If you can travel even further down there we can reduce the weight of the highlight.js library

Importing all 192 languages will increase the size of the page weight and load time, but you can import them individually to reduce the weight

Here is an example

Self-hosting highlight.js

Instead of using a third-party resource, it is better to self-host highlight.js

But why?

To fix, “reduce third party resources”  and “render blocking “issues in pagespeed insight

But how do I host highlight.js?

  1. Go to the download section of the highlight.js library
  2. Choose the required languages
  3. Download the .zip file and extract it
  4. now you need to find two files[your-theme.css and highlight.min.js]
  5. create a new directory called libraries in your child theme through FileZilla
  6. import these two files [your-theme.css and highlight.min.js]into your new directory called libraries
  7. link the path of your director to the header or footer of your site

Here is how I self-hosted highlight.js on my site

<link rel="stylesheet" href="https://aneescraftsmanship.com/wp-content/themes/werkstatt-child/anees-libraries/highlight.js-library/atom-one-dark.css">
<script  src="https://aneescraftsmanship.com/wp-content/themes/werkstatt-child/anees-libraries/highlight.js-library/highlight.min.js"></script>
<script>hljs.highlightAll();</script>

By editing the theme file editor

Let’s see a second way to install the highlight.js library on WordPress

  1. open your WordPress dashboard And hover over appearance then select theme file editor
  2.  on the right side you should see a header.php or a footer.php file
  3. You can copy and paste the previous four tags of the library as mentioned either in header.php or footer.php

Now, the code looks cleaner, but I like to add a copy to the clipboard button.

But, how to do that?

Here is a script to create a copy to clipboard button on code and you can add this script to the header or footer of your site.

<!------copy button script ------->
<script>
document.addEventListener('DOMContentLoaded', function() {
    var codeBlocks = document.querySelectorAll('.wp-block-code');
    codeBlocks.forEach(function(block) {
        var code = block.querySelector('code');
        var button = document.createElement('button');
        var buttonText = document.createTextNode('Copy Code');
        button.appendChild(buttonText);
        button.style.cssText = 'position: absolute; top: 0; right: 0; margin: 4px; padding: 4px 8px; font-size: 12px; background-color: rgba(200, 200, 200, 0.2); color: #fff; border: none; border-radius: 4px; cursor: pointer; transition: all 0.2s ease-in-out;';
        button.addEventListener('mouseenter', function() {
            button.style.backgroundColor = 'rgba(0, 0, 0, 0.1)';
        });
        button.addEventListener('mouseleave', function() {
            button.style.backgroundColor = 'rgba(200, 200, 200, 0.2)';
        });
        button.addEventListener('click', function() {
            var range = document.createRange();
            range.selectNode(code);
            window.getSelection().addRange(range);
            document.execCommand('copy');
            window.getSelection().removeAllRanges();
            button.innerText = 'Copied!';
            button.style.backgroundColor = '#333';
            button.style.color = '#fff';
            setTimeout(function() {
                button.innerText = 'Copy Code';
                button.style.backgroundColor = 'rgba(200, 200, 200, 0.2)';
                button.style.color = '#fff';
            }, 3000);
        });
        block.style.cssText = 'position: relative;';
        block.insertBefore(button, code);
    });
    var codeTexts = document.querySelectorAll('.wp-block-code pre');
    codeTexts.forEach(function(text) {
        text.style.color = '#fff';
    });
});
</script>

Mohammed Anees

Hey there, welcome to aneescraftsmanship I am Mohammed Anees an independent developer/blogger. I like to share and discuss the craft with others plus the things which I have learned because I believe that through discussion and sharing a new world opens up

Leave a Reply

Your email address will not be published.