核心目标:不依赖插件,在Astra主题中集成Parsedown解析器,仅对「文章」生效(排除页面、自定义文章类型),轻量可控,解决此前代码报错问题,适用于有基础PHP能力的开发者。
一、核心准备
- 工具:FTP(或WordPress主题文件编辑器)、Parsedown解析器(单个PHP文件)
- Parsedown下载:https://parsedown.org/(仅需下载Parsedown.php)
二、关键步骤(必做,适配Astra主题)
- 存放Parsedown.php(路径不可错)
适配Astra主题的路径:wp-content/themes/astra/extend/Parsedown.php
操作:在Astra主题根目录(wp-content/themes/astra/)下,新建extend文件夹,将下载的Parsedown.php上传至此。 - 编辑Astra主题functions.php(修复报错,仅文章生效)
打开Astra主题的functions.php(路径:wp-content/themes/astra/functions.php),在文件底部粘贴以下代码(已修复is_post()报错,仅对文章生效):// 加载Parsedown解析器(路径适配Astra主题) require_once get_template_directory() . '/extend/Parsedown.php'; // 解析文章内容为Markdown(仅对文章生效,修复is_post()报错) function wp_parsedown_content($content) { // 用get_post_type() === 'post'判断,仅文章生效,排除页面等 if (get_post_type() === 'post' && is_singular() && in_the_loop() && is_main_query()) { $Parsedown = new Parsedown(); $Parsedown->setBreaksEnabled(true); // 支持换行符自动转<br/> $content = $Parsedown->text($content); } return $content; } add_filter('the_content', 'wp_parsedown_content'); // 禁用WordPress自动格式化,避免Markdown语法冲突 remove_filter('the_content', 'wpautop'); remove_filter('the_content', 'wptexturize'); - 测试验证
- 新建「文章」(注意:不是”页面”),切换至「文本模式」,输入Markdown语法(如# 标题、**加粗**、代码块);
- 发布文章,前端查看,若语法正常渲染,即完成;
- 测试页面:新建「页面」,输入Markdown语法,发布后不会解析(验证仅文章生效)。
三、核心避坑(必看,避免报错和失效)
- 路径必须适配Astra主题:确保Parsedown.php存放在
wp-content/themes/astra/extend/,路径错误会导致网站白屏; - 报错修复重点:禁止使用is_post()函数(WordPress无此函数),必须用
get_post_type() === 'post'判断文章类型; - 编辑模式:仅在「文本模式」写Markdown,可视化模式会导致语法失效;
- 禁用自动格式化:不可删除代码最后两行,否则会出现Markdown格式错乱;
- Astra主题更新:主题更新会覆盖functions.php代码,建议使用Astra子主题,将代码添加到子主题的functions.php中。
四、可选优化(按需添加)
- 代码高亮:在Astra主题的style.css底部添加简单CSS,实现代码块灰色背景、横向滚动,提升可读性;
- 条件解析:取消代码中注释,添加自定义字段
is_markdown(值为true),仅标记的文章解析Markdown。
总结:核心3步(上传解析器→粘贴修复后代码→测试),适配Astra主题,解决报错问题,仅对文章生效,轻量无插件依赖,避开路径和函数报错两个核心坑即可稳定使用。
