前言
有一个想法,需要去实现,不想装一个超级笨重的插件实现Markdown,本就很简单的东西,或许直接在主题上是拓展出来。
最近拖延症越来越严重,睡过头,失眠等等。
实现
没有细节,没有原理,没有解释,枯燥的带着自己的心情写下去。
- 
第一步,安装markdown解析器,为什么要用这个解析器呢,用就对了。哪天不喜欢了再换,但是真的会去换么。 cd wordpress/wp-content/theme-name/
 composer require erusev/parsedown
- 
第二步,添加内容解析 在 functions.php添加如下内容,关键点the_content和-2000,如果这个优先级还不够高,那么就-20001,这样就可以每次打开文章都会优先解析Markdown了<?php
 function process_markdown_content($content)
 {
 $Parsedown = new Parsedown();
 $Parsedown->setSafeMode(false);
 $content = $Parsedown->text($content);
 $content = preg_replace_callback_array([
 "#<pre><code>([\w\W]+?)<\\/code><\\/pre>#" => function ($arg) {
 return "<code lang="text" escaped="true">{$arg[1]}</code>";
 },
 "#<pre><code class="language-([\w\W]+?)">([\w\W]+?)<\\/code><\\/pre>#" => function ($arg) {
 if (in_array($arg[1], ["raw_text", "raw"])) {
 return "<pre>{$arg[2]}</pre>";
 } else {
 return "<code lang="{$arg[1]}" escaped="true">{$arg[2]}</code>";
 }
 },
 "#<code>([\w\W]+?)<\\/code>#" => function ($arg) {
 return "<code escaped="true" inline="true">{$arg[1]}</code>";
 },
 ], $content);
 
 return $content;
 }
 function is_markdown_post($post_id)
 {
 $is_markdown = get_post_meta($post_id, "is_markdown", true);
 return in_array($is_markdown, [1, "1", "true", "markdown"]);
 }
 function the_markdown_content_filter($content)
 {
 global $post;
 if (is_markdown_post($post->ID)) {
 $content = process_markdown_content($content);
 }
 return $content;
 }
 add_filter('the_content', 'the_markdown_content_filter', -2000);这断代码中有几个关于代码内容替换的操作,不指望能理解,只想提一个关键字 codecolorer,或许作用就在那里,效果是怎么样的呢,这篇内容就是
- 
第三步,为新文章添加支持,旧文章不管  让新的博客文章支持Markdown 原因就不解释了,没人愿意去改旧文章,除非情不得已。实现是前面代码中的 get_post_meta($post_id, "is_markdown", true),这里可以添加其他内容实现不一样的效果,还是蛮简单的。
- 
第四步,添加专用的Markdown样式,如果你的现有样式很好可以忽略 先是PHP相关内容的改动,PHP的支持还是有点麻烦的,要改好几个地方,感觉实现一点都不优雅。 <?php
 //modfiy on functions.php
 function theme_markdown_content_class(): string
 {
 if (is_single()) {
 global $post;
 if (is_markdown_post($post->ID)) {
 return " markdown-body";
 }
 }
 return "";
 }
 ?>
 
 <!-- //modify on content.php. if more, repeat it. -->
 <div class="entry-content<?=theme_markdown_content_class()?>">
 <?php
 the_content('继续阅读 <span class="meta-nav">→</span>');
 wp_link_pages(array(
 'before' => '<div class="page-links"><span class="page-links-title">' . __('Pages:') . '</span>',
 'after' => '</div>',
 'link_before' => '<span>',
 'link_after' => '</span>',
 ));
 ?>
 </div>样式文件支持,可以参考Github项目: https://github.com/sindresorhus/github-markdown-css ,如果有更好的我一定换,这个效果也并不太好 
后文
改了一堆东西,复制了一堆东西,效果还可以,同时还兼容了现有的文章。图片代码什么的也完美兼容,嗯,还不错,比心情好许多。

我的破站很久没有折腾了,WP折腾这个感觉好卡,TYPECHO倒是自带,可惜我对Markdown不熟悉,不怎么能会用。
第三步,每次写太麻烦了。可以在后台发布那个地方加个选项,手动设定要不要加那个is_markdown到post_meta里,默认选中。估计用不上10行代码。搜“post_submitbox_misc_actions”就行。
或者利用draft_to_publish,new_to_publish的钩子,3行就够了。
这种细节的东西都是很容易的,够用就行,那天觉得烦了再改