Php Wordpress获得帖子上的第一张附加图片
今天,我尝试使用以下代码显示wordpress中最受欢迎的帖子: 它工作得很好,但是它不允许我抓取帖子上的第一张附加图片。我需要这样做,以便从保存图像的任意自定义字段中获取图像 我尝试使用下面的代码(实际上可以在另一个自定义项上使用)来获取文章中的第一个附加图像,但我一直无法使其正常工作Php Wordpress获得帖子上的第一张附加图片,php,wordpress,Php,Wordpress,今天,我尝试使用以下代码显示wordpress中最受欢迎的帖子: 它工作得很好,但是它不允许我抓取帖子上的第一张附加图片。我需要这样做,以便从保存图像的任意自定义字段中获取图像 我尝试使用下面的代码(实际上可以在另一个自定义项上使用)来获取文章中的第一个附加图像,但我一直无法使其正常工作 $p = array( 'post_type' => 'attachment', 'post_mime_type' => 'image', 'numberposts' =&
$p = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => 1,
'order' => 'ASC',
'orderby' => 'menu_order ID',
'post_status' => null,
'post_parent' => $post->ID
);
$thumb = get_posts($p);
if ($thumb) {
$imgsrc = wp_get_attachment_image_src($thumb[0]->ID, 'thumbnail');
$img = $imgsrc[0];
}
有什么方法可以做到这一点吗???您可以使用此代码获取帖子的第一个附件图像:
$catposts = get_posts('category='.$category_id."&order=DESC&numberposts=".$NUMBEROFPOSTS);
function catch_that_image($_catposts)
{
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $_catposts->post_content, $matches);
$first_img = $matches[1][0];
return $first_img;
}
$j=0;
foreach ($catposts as $item) :
$get_contents = $item->post_content;
$regex_pattern = "/<a href=\"(.*)\">(.*)<\/a>/";
$output = preg_match_all($regex_pattern,$item->post_content, $matches);
echo '<img src="'.catch_that_image($catposts[$j]).'" alt="" border="0px" />';
$j++;
endforeach;
$catposts=get_posts('category='.$category_id.&order=DESC&numberposts=“.$NUMBEROFPOSTS”);
函数捕捉图像($\u CATPOST)
{
$first_img='';
ob_start();
ob_end_clean();
$output=preg\u match\u all('//i',$\u catposts->post\u content,$matches);
$first_img=$matches[1][0];
返回$first\u img;
}
$j=0;
foreach($catposts作为$item):
$get\u contents=$item->post\u content;
$regex_pattern=“/(.*)/”;
$output=preg\u match\u all($regex\u模式,$item->post\u内容,$matches);
回声';
$j++;
endforeach;
其中$category\u id是特定的类别id。假设您有一个category id=26,那么所有26个category post都显示在foreach循环中
在相关帖子上,显示您在帖子中输入的第一个图像
谢谢。尝试将
$attachments[0]->ID
更改为$thumb[0]->ID
如果调试$thumb
的内容是什么?它工作得很好,但是我试图完成的是从post meta上的任何字段获取帖子。您的代码将只搜索插入帖子内容中的任何图像。我需要搜索贴在帖子上的任何图片(无论是在描述中还是在特色图片、自定义字段等上)