如何在WordPress中仅显示文章的特定内容(如段落)
解决方案:WordPress前端仅展示文章段落内容
下面提供三种可靠的实现方式,按需选择:
1. 修改主题模板文件(精准控制页面)
找到你主题中负责显示文章内容的模板文件(如single.php、page.php或自定义文章类型模板),替换原有the_content()调用为以下代码:
<?php $content = get_the_content(); $dom = new DOMDocument(); // 处理UTF-8编码与HTML解析警告 libxml_use_internal_errors(true); $dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8')); libxml_clear_errors(); // 遍历并输出所有<p>标签内容 $paragraphs = $dom->getElementsByTagName('p'); foreach ($paragraphs as $p) { echo $dom->saveHTML($p); } ?>
原理:用DOM解析器精准提取所有<p>标签内容,避免正则表达式匹配的兼容性问题。
2. 使用过滤器钩子(全局/条件生效)
无需修改模板,在主题的functions.php中添加以下代码,可全局或针对特定页面生效:
function filter_only_paragraphs($content) { // 限定生效范围:单篇文章/页面,可根据需求修改(如is_post_type('custom')) if (is_single() || is_page()) { $dom = new DOMDocument(); libxml_use_internal_errors(true); $dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8')); libxml_clear_errors(); $new_content = ''; $paragraphs = $dom->getElementsByTagName('p'); foreach ($paragraphs as $p) { $new_content .= $dom->saveHTML($p); } return $new_content; } // 非目标页面返回原内容 return $content; } add_filter('the_content', 'filter_only_paragraphs');
优势:无需修改多个模板文件,通过条件判断灵活控制生效场景。
3. 短代码(手动控制单篇文章)
如果仅需在特定文章中生效,在functions.php中添加短代码函数:
function only_paragraphs_shortcode($atts) { $content = get_the_content(); $dom = new DOMDocument(); libxml_use_internal_errors(true); $dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8')); libxml_clear_errors(); $new_content = ''; $paragraphs = $dom->getElementsByTagName('p'); foreach ($paragraphs as $p) { $new_content .= $dom->saveHTML($p); } return $new_content; } add_shortcode('only_paragraphs', 'only_paragraphs_shortcode');
之后在文章编辑页面,直接插入短代码[only_paragraphs]即可替换为仅段落内容。
注意事项
- 上述代码均使用DOM解析而非正则,避免因HTML结构不规范导致的匹配失败;
libxml_use_internal_errors(true)用于屏蔽HTML解析时的非致命警告,不影响功能;- 若需保留段落内的子元素(如
<a>、<em>),代码无需修改,会自动保留。
内容的提问来源于stack exchange,提问作者Misterjozni
相关产品推荐
相关产品推荐

