如何从特定页面模板上的the_content()中删除包含和不包含环绕链接的所有图像

时间:2013-02-14 16:02:29

标签: php wordpress dom

我正在尝试从<img>围绕<a>标记所有the_content()的特定页面模板。我已经找到了一些解决方案,包括preg_replace和使用get_the_content(),但在使用get_the_content()时,段落周围没有<p>

如何在网页模板上过滤the_content()以删除所有<a><img></a><img>代码?

我被告知here不要使用preg_replace而是DOM。 一些推动正确的方向将是伟大的,因为我是一个PHP菜鸟。

1 个答案:

答案 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(']]>', ']]&gt;', $no_image_content);
echo $no_image_content;