我正在尝试从<img>
围绕<a>
标记所有the_content()
的特定页面模板。我已经找到了一些解决方案,包括preg_replace
和使用get_the_content()
,但在使用get_the_content()
时,段落周围没有<p>
。
如何在网页模板上过滤the_content()
以删除所有<a><img></a>
和<img>
代码?
答案 0 :(得分:0)
好的我会回答我自己的问题,但首先要感谢Gordon让我朝着正确的方向前进。我的结果基于stackoverflow上的this问题。
它使用DOM
而非preg_replace()
,就像我在很多例子中看到的那样
有一点需要提及的是,我需要使用get_the_content()
而不是the_content()
,因为the_content()
回应了过滤结果。但在codex中提示如何过滤get_the_content()
以获得与the_content()
相同的输出。
这是执行我想要的代码:
$dom = new DOMDocument;
$dom->loadHTML(get_the_content());
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//img|//a[img]');
foreach($nodes as $node) {
$node->parentNode->removeChild($node);
}
$no_image_content = $dom->saveHTML();
$no_image_content = apply_filters('the_content', $no_image_content);
$no_image_content = str_replace(']]>', ']]>', $no_image_content);
echo $no_image_content;