【问题标题】:Need to get all <img> from the_content(); in wordpress?需要从the_content()中获取所有<img>;在wordpress中?
【发布时间】:2017-01-02 04:56:54
【问题描述】:

我最近刚刚将博客网站上的所有内容导入 wordpress,我需要整理一下。

我在 single.php 中工作,我想从 the_content(); 获取每个 &lt;a&gt;&lt;img src=""/&gt;&lt;/a&gt;。我的 php 充其量是有点粗制滥造。

我知道这可以让我获得帖子的第一张图片,但我需要类似的东西,可以让我获得来自 the_content(); 的所有图片(不是精选图片)。

function catch_that_image() {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    $first_img = $matches[1][0];

    if(empty($first_img)) {
        $first_img = "/path/to/default.png";
    }
    return $first_img;
} 

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    看看 PHP 的原生 DOMDocument 对象。 http://www.php.net/manual/en/class.domdocument.php

    您将获取您的内容并通过loadHTML() 将其加载到 DOMDocument 中。那么你可以使用getElementsByTagName()来获取所有图片。

    http://www.php.net/manual/en/domdocument.getelementsbytagname.php

    $document = new DOMDocument();
    $document->loadHTML($post->post_content);
    $images = $document->getElementsByTagName('img');
    

    【讨论】:

    【解决方案2】:

    DOMDocument 的小任务:

    $doc = new DOMDocument();
    $doc->loadHTML($post->post_content);
    foreach ($doc->getElementsByTagName('img') as $img)
        $img->attributes['src'] = '/path/to/default.png'; // or whatever you want to do
    return $doc->saveHTML();
    

    您需要注意,saveHTML() 可能会在您的结构周围添加缺失的标签。

    【讨论】:

    • 哈,太好了,这就是我喜欢听的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 2015-11-05
    • 1970-01-01
    • 2010-09-20
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多