php - 需要从 the_content() 获取所有 <img>;在 WordPress 中?

标签 php wordpress

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

我在 single.php 中工作,我想得到每个 <a><img src=""/></a>来自 the_content(); .我的 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 的 native 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');

关于php - 需要从 the_content() 获取所有 <img>;在 WordPress 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20861875/

相关文章:

php - 如何在MySQL 5中选择一个类别和子类别中的所有文章

wordpress - 元标记描述中的错误未显示

php - WordPress 错误 : There has been a critical error on your website. 请检查您的站点管理员电子邮件收件箱以获取说明

wordpress - PDF 文件免受外部访问。仅可供经过身份验证的用户访问。 WordPress上传目录

php - 这些字符串的正确检查语法是什么?

php - 我正在使用 C 语言的 libcurl 库编写一个 REST API 来登录我的网页

php - 即使值不存在于 where 子句中也得到返回

php - Postgresql自定义函数返回表

php - 激活插件时创建自定义帖子类型,并在停用后删除 -Wordpress

wordpress - Nginx,Wordpress和SQL