How to Easily Embed Gist Code Snippets in WordPress Posts Without a Dedicated Plugin or Code

WordPress’s native solution for embedding code snippets in the block editor isn’t great. Here is how to enable a good alternative.

The problem: native Code block lacks readability

If you run a development blog, embedding code snippets in the block editor is a common task. WordPress’s block editor has a native Code block for that purpose. It looks like this:

<?php $query_args = array( 'foo' => 'bar', 'apple' => 'orange', 'posts_per_page' => 50, 'offset' => 0, ); $some_posts = new WP_Query( $query_args ); while ( $some_posts->have_posts() ) { /* * Do some stuff here */ // Get more posts $query_args['offset'] = $query_args['offset'] + $query_args['posts_per_page']; $some_posts = new WP_Query( $query_args ); }
Code language: HTML, XML (xml)

If you see syntax highlighting here it is because I’m testing the Syntax-highlighting Code Block plugin, for SEO reasons. Read about it in this post.


Usually, I’m a big fan of native, simple solutions. But this one just isn’t good enough. When it comes to code, readability is essential. Unfortunately, the native Code block lacks syntax highlighting, and overall isn’t formatted for easy reading.

The solution: embed gist snippets in the block editor

Github has a great tool for sharing code snippets called gists. Gists support syntax highlighting and are formatted for easy reading. You are probably familiar with them. They look like this:

Much better, isn’t it?

Inconveniently, you can’t embed gists in the block editor out-of-the-box. But, Jetpack’s Shortcode Embeds option makes embedding gists possible.

These are the steps for enabling Jetpack’s Shortcode Embeds option, and embedding a gist in the block editor:

  1. Enable the “Compose using shortcodes to embed media from popular sites” Jetpack option

    – On the Jetpack dashboard, click Settings.
    – Using the search bar, search for ‘shortcode’.
    – Under Writing > Composing, enable ‘Compose using shortcodes to embed media from popular sites’.

  2. Copy the gist’s URL

  3. Paste it on the block editor. It will be recognized as a shortcode.

    Note: You might not see the gist in the block editor. Preview the post to check.

Conclusion

When sharing code snippets in your posts, readability is essential. Unfortunately, The native Code block isn’t formatted for easy reading. It lacks, for example, syntax highlighting. Gists, on the other hand, support syntax highlighting and are much more readable. Although gists can’t be embedded in the block editor out-of-the-box, a hidden Jetpack setting allows you to easily embed gists in your posts.


While solving readability, embedded gists probably introduce SEO issues. As such, they aren’t a perfect solution. Read about it, and about another non-perfect solution, here.


External links

Leave a comment

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