我最近刚刚将博客网站的所有内容导入到 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/