LD
Change your colour scheme

Using WordPress as a Markdown editor

Published:

The eagle-eyed among you will notice that my website’s had a slight refresh - and by that I mean I got bored of that ZX Spectrum theme roughly 45 seconds after publishing it.

I’ve also switched back to Eleventy! I’m still using Wordpress though, because I didnt’ want to migrate. I did, however, want to make it easier to migrate in the future. I’ve also got a nice Markdown configuration that I’m quite comfortable with, so I’d like to use that too.

So, I need to somehow use Wordpress as a markdown editor… sounds silly, probably is, but I’m gonna do it anyway.

I already had the WP Githuber MD extension installed from when I originally migrated to Wordpress. It’s quite handy because it comes with a utility that converts between Wordpress posts and Markdown. It achieves this by storing the unrendered Markdown content alongside posts.

That solves the first half of the problem - I just needed to go through and convert all my posts, which was a pretty quick job.

Next, I need to be able to get that Markdown content. The Wordpress REST API obviously doesn’t return this by default, and the plugin doesn’t extend the API for us. So, I’ll need to write a little plugin myself that uses register_rest_field to add the markdown content to the post:

add_action( 'rest_api_init', 'add_md_to_rest');

function add_md_t_rest() {
register_rest_field( 'post', 'markdown', array(
'get_callback' => function( $post_arr ) {
return html_entity_decode(get_post_field('post_content_filtered', $post_arr['id'], 'edit'), ENT_QUOTES | ENT_HTML5, 'UTF-8');
},
'update_callback' => function( $karma, $comment_obj ) {
return true;
},
'schema' => array(
'description' => __( 'Markdown content.' ),
'type' => 'string'
),
) );
}

Now, when I fetch new posts from my Wordpress API, they have a markdown field, containing the unrendered markdown.

Then, finally, in my template I have a filter that directly calls markdownIt.render on a passed string, and I use that to render the content of my post:

eleventyConfig.addFilter('md', content => content ? markdownLib.render(content) : "");
{{ post.markdown | md | safe }}

About the author

My face

I'm Lewis Dale, a software engineer and web developer based in the UK. I write about writing software, silly projects, and cycling. A lot of cycling. Too much, maybe.

Responses