Using Jetpack’s Markdown with Timber

Jetpack’s Markdown implementation works well for post and comment content, but does not provide hooks for use on custom fields. As part of a recent project that uses Markdown extensively in ACF fields, I put together the following implementation for leveraging Timber and Jetpack to convert Markdown in Twig views. The implementation uses Timber’s get_twig WordPress filter hook. This filter passes in the $twig object used by Timber and can be used to add Twig filters and functions.

The following filter checks to see if Jetpack’s Markdown module is active and uses it to convert a string to HTML.

The markdown Twig filter can be used in the Twig view as any other, for example:

One caveat to this approach, conversion of Markdown to HTML at render could be slow. The Jetpack Markdown module converts post content on save (and saves to post_content_filtered). Make sure to use page caching or Twig template caching.