---
title: "Using WordPress as a Markdown editor"
date: 2023-02-18T21:56:35
slug: using-wordpress-as-a-markdown-editor

---
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](https://github.com/terrylinooo/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](https://developer.wordpress.org/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:

```php
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:

```javascript
eleventyConfig.addFilter('md', content => content ? markdownLib.render(content) : "");
```

{% raw %}
```twig
{{ post.markdown | md | safe }}
```
{% endraw %}