搜索了好几个小时都没有成功。我的问题很简单,但答案似乎难以捉摸。我想在每个自定义帖子类型的帖子中分别显示前三个附件图像。下面的代码已经让我在那里的一部分,但我不确定如何进行?
<?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');
} ?>
好的,在这里添加了附件转储:
Array
(
[106] => WP_Post Object
(
[ID] => 106
[post_author] => 2
[post_date] => 2013-03-13 13:38:11
[post_date_gmt] => 2013-03-13 12:38:11
[post_content] =>
[post_title] => autumn_leaves_new2
[post_excerpt] =>
[post_status] => inherit
[comment_status] => open
[ping_status] => open
[post_password] =>
[post_name] => autumn_leaves_new2
[to_ping] =>
[pinged] =>
[post_modified] => 2015-08-15 06:01:05
[post_modified_gmt] => 2015-08-15 06:01:05
[post_content_filtered] =>
[post_parent] => 278
[guid] => http://localhost/pbvcid/wp
content/uploads/2013/03/autumn_leaves_new2.jpg
[menu_order] => 0
[post_type] => attachment
[post_mime_type] => image/jpeg
[comment_count] => 0
[filter] => raw
)
我想我的解释需要更清楚一点。我提供的代码只是一个开始,因为我的php知识有限。我相信我正在寻找的是一种将自定义帖子类型附件放入索引数组的方法,以便我可以从该数组中选择几个单独的附件,并在自己的单独div中显示它们。到目前为止,代码没有有效地运行,并且没有显示帖子中的所有附件,(感谢所有的帮助到目前为止btw)。
找到正确显示数组的解决方案:
$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>
试试这个
$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 $image ) {
echo wp_get_attachment_image( $image->ID, 'medium' );
}
如果这不起作用,则转储附件变量并将结果返回到这里,
你可以像这样转储
echo '<pre>', print_r($attachments, 1), '</pre>';
试试下面的代码来获取附件。
<?php
$attachments = get_children( array(
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
'numberposts' => 3,
'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');
} ?>