如何从特定页面模板中的__entent()中删除所有包含或不带有酸性链接的图像 [英] How to remove all images with and without sourrounding links from the_content() on specific page template

查看:114
本文介绍了如何从特定页面模板中的__entent()中删除所有包含或不带有酸性链接的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图剥夺所有< img> ,包含&不包含< a> 标签 the_content()为特定页面模板。我已经找到一些解决方案,包括 preg_replace ,并使用 get_the_content(),但使用 get_the_content() 周围没有< p>

I'm trying to strip all <img> with and without surrounding <a> tags from the_content() for a specific page template. I already found some solutions including preg_replace and using get_the_content() but when using get_the_content() there are no <p> surrounding the paragraphs.

如何在页面模板上过滤 the_content()以删除所有一个>< img>< / a> < img>

How could I filter the_content() on a page template to remove all <a><img></a> and <img> tags?

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

I've been adviced here not to use preg_replace for that but rather DOM. Some push in the right direction would be great because I'm a PHP rookie.

推荐答案

好的,我会回答我自己的问题,但首先感谢 Gordon 推动我走向正确的方向。我的结果是基于这个问题在这里stackoverflow。

Okay I will answer my own question, but first thanks to Gordon for pushing me into the right direction. My result is based on this question here on stackoverflow.

它使用 DOM 而不是 preg_replace()像我在很多例子上看到的一样。

有一件事要提到的是我需要使用 get_the_content()而不是 the_content()因为 the_content()回过滤结果。但是 codex 是一个提示如何过滤 get_the_content()实现与 the_content()相同的输出。

It uses DOM and not preg_replace() like I saw it on many examples.
One thing to mention is that I need to use get_the_content() instead of the_content() because the_content() echos a filtered result. But in the codex is a hint how to filter get_the_content() to achieve the same output as 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;

这篇关于如何从特定页面模板中的__entent()中删除所有包含或不带有酸性链接的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆