Publish: 2018-07-28 | Modify: 2018-07-31
WordPress does not support MarkDown markup by default (not sure if the latest version has implemented it yet). Although there are many third-party MarkDown plugins available, none of them provide satisfactory results. I have always used HTML tags to write articles, which have good formatting effects, but it is really cumbersome to write and not efficient. So I came up with a way to make WordPress better support MarkDown syntax without installing additional plugins.
Parsedown can parse MarkDown content into HTML. If the content is already in HTML, it will not be parsed. With the support of Parsedown, when publishing WordPress articles, it can not only be compatible with the original text mode (HTML), but also use MarkDown syntax for writing, and the two do not conflict.
extend
in the theme directory.Parsedown.php
into the extend
directory.Add the following code to the functions.php
file in the theme directory to register it as a WordPress hook:
// Markdown parsing
function wp_parsedown(){
include_once(get_stylesheet_directory()."/extend/Parsedown.php");
$Parsedown = new Parsedown();
$content = get_the_content();
$content = $Parsedown->text($content);
if(is_single() || is_page()){
echo $content;
}
else{
$content = strip_tags($content);
$content = mb_substr($content,0,180,'UTF-8');
echo $content;
}
}
add_action('the_content','wp_parsedown');
If the external links in the article need to be automatically added with nofollow
and open in a new window, please use the following code:
// Markdown parsing, add nofollow
function wp_parsedown(){
include_once(get_stylesheet_directory()."/extend/Parsedown.php");
$Parsedown = new Parsedown();
$content = get_the_content();
$content = $Parsedown->text($content);
if(is_single() || is_page()){
preg_match_all('/href="(.*?)"/',$content,$matches);
if($matches){
foreach($matches[1] as $val){
if( strpos($val,home_url())===false ) $content=str_replace("href=\"$val\"",
"href=\"$val\" rel=\"external nofollow\" target = \"_blank\" ",$content);
}
}
echo $content;
}
else{
$content = strip_tags($content);
$content = mb_substr($content,0,180,'UTF-8');
echo $content;
}
}
add_action('the_content','wp_parsedown');
Note the line $content = mb_substr($content,0,180,'UTF-8');
, where 180 represents the number of words in the article summary on the homepage. Please modify it according to your own situation.
WordPress text mode supports HTML writing. With the above steps, the text mode now perfectly supports MarkDown syntax.
This method is simple to operate and does not require the installation of additional plugins. It is fully compatible with the original text mode. When writing this article, I have been using MarkDown, so you can see the effect.
I come from China and I am a freelancer. I specialize in Linux operations, PHP, Golang, and front-end development. I have developed open-source projects such as Zdir, ImgURL, CCAA, and OneNav.