我试图在自定义帖子类型的每个帖子中分别显示前三个附件图像。我相信我正在寻找的是一种将自定义帖子类型的附件放入索引数组的方法,这样我就可以从该数组中选择几个单独的附件,并将它们显示在各自的div中。到目前为止,代码的运行效率不高,无法显示帖子中的所有附件。我所提供的代码只是一个扩展的开始,它让我在一定程度上做到了这一点,但我不确定如何继续,因为我的php知识有限。
$attachments = get_children( array(
\'post_parent\' => get_the_ID(),
\'post_type\' => \'attachment\',
\'numberposts\' => -1,
\'post_status\' => \'inherit\',
\'post_mime_type\' => \'image\',
\'order\' => \'ASC\',
\'orderby\' => \'menu_order ASC\'
) );
foreach ( $attachments as $attachment_id => $attachment ) {
echo wp_get_attachment_image( $attachment_id, \'medium\');
}
最合适的回答,由SO网友:Paubab 整理而成
设法找到正确显示阵列的解决方案:
$attachments = get_children( array(
\'post_parent\' => get_the_ID(),
\'post_type\' => \'attachment\',
\'numberposts\' => -1,
\'post_status\' => \'inherit\',
\'post_mime_type\' => \'image\',
\'order\' => \'ASC\',
\'orderby\' => \'menu_order ASC\'
) );
$imgArray = array();
$counter = 0;
foreach ( $attachments as $attachment_id => $attachment ) {
$imgArray[$counter] = $attachment_id;
$counter++;
if($counter > 2) {
break;
}
}
?>
<div class="attachment1"><?php echo wp_get_attachment_image( $imgArray[0], \'medium\'); ?></div>
<div class="attachment2"><?php echo wp_get_attachment_image( $imgArray[1], \'medium\'); ?></div>
<div class="attachment3"><?php echo wp_get_attachment_image( $imgArray[2], \'medium\'); ?></div>