Markdown comments in WordPress

Created on

18 Feb 2020

Updated on

20 Jan 2021

While there are a lot of plugins that enable markdown in the editor or on custom admin pages, I couldn’t find a plugin that supports markdown in comments. So I decided to implement one on my own.

To convert the text to markdown, we will be using the awesome Parsedown library.

Installation

To get started, download and copy the Parsedown.php file into the root of your theme.

Now, there are two options to implement markdown in comments. The first one is to parse the comment before it is inserted into the database. And the second one is to parse the comment before it is displayed.

Method 1

Converting the comments to markdown before it is inserted into the database.

Open your theme’s functions.php and paste the below code.

function comment_to_markdown( $comment_data ) {
    include_once "parsedown.php";
    
    $Parsedown = new Parsedown();
    $Parsedown->setSafeMode(true);
    
    $comment_data["comment_content"] = $Parsedown->text($comment_data["comment_content"]);
    return $comment_data;
}
add_filter( 'preprocess_comment', 'comment_to_markdown' );

The above filter will parse the markdown in a comment before it is inserted. So already existing comments are not parsed.

This method is useful if you’re using REST API for retrieving comments.

Method 2

Parse the comment before displaying it.

Here the comment is parsed just before displaying it to the screen, so the value in the database is not changed.

To implement this method, paste the below code into your theme’s functions.php file

function comment_to_markdown( $comment_text, $comment = null ) {
    include_once "parsedown.php";
    
    $Parsedown = new Parsedown();
    $Parsedown->setSafeMode(true);
    
    $comment_text = $Parsedown->text($comment_text);
    return $comment_text;
}
add_filter( 'comment_text', 'comment_to_markdown', 5, 2 );

That’s it! Choose any of the two methods to implement markdown supported comments.

Comments

Post a comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.