我正在尝试从特定页面模板中剥离所有<img>带有和不带有周围<a>标签的内容。the_content()我已经找到了一些解决方案,包括preg_replace和使用get_the_content(),但是在使用时get_the_content()没有<p>围绕段落。
如何过滤the_content()页面模板以删除所有<a><img></a>标签<img>?
好的,我会回答我自己的问题,但首先感谢Gordon将我推向正确的方向。我的结果是基于stackoverflow上的这个问题。
它使用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;