Markdown comments in WordPress

18 Feb 2020

18 Feb 2020

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

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

Latest Posts

WordPress lazy load images with blur up technique

WordPress lazy load images with blur up technique

18 Mar 2020

Lazy loading images in WordPress with blur up technique.

Create options page in WordPress using free ACF

Create options page in WordPress using free ACF

17 Feb 2020

Create a custom settings page for your WordPress site using ACF free version.

Sidenav using pure css

Sidenav using pure css

20 Apr 2019

Pure CSS side nav with toggle controls.

Sliced text in CSS

Sliced text in CSS

20 Mar 2019

Create sliced/glitch text effect using CSS

Pure CSS modal

Pure CSS modal

19 Mar 2019

Pure CSS Modal with close/open buttons as well as click outside to close ability.

Create animated donut chart using SVG and javascript

Create animated donut chart using SVG and javascript

05 Feb 2019

Animated donut chart using SVG, javascript, and CSS.