我想从帖子中检索所有图像附件,并将其渲染到图库中。有些人认为返回的附件数量只有一个,即使帖子包含多个图像附件也很难。奇怪的是,一些被返回的附件甚至没有出现在帖子中。下面是我用来获取附件的函数
function get_attchments($num=1){
$output = \'\';
if (has_post_thumbnail() && $num == 1){
$output = wp_get_attachment_url(get_post_thumbnail_id(get_the_ID()));
}else {
$attachments = get_posts(array(
\'post_type\' => \'attachment\',
\'posts_per_page\' => $num,
\'exclude\' => get_post_thumbnail_id(),
\'post_parent\' => get_the_ID(),
));
if ($attachments && $num == 1){
foreach ($attachments as $attachment){
$output = wp_get_attachment_url($attachment->ID);
}
}else if($attachments && $num > 1){
$output = $attachments;
}
wp_reset_postdata();
}
return $output;
}
我调用函数如下
while(have_posts()){
the_post();
$def_class=\'twigs\';
set_query_var(\'lighter_def_post_class\', \'twigs\');
get_template_part(\'template-parts/content\', get_post_format() );
}
这是contenet gallery的代码。php
$attachments = get_attchments(7);
foreach( $attachments as $attachment ){
//I am rendering the images out here
}
我早就有这个问题了。非常感谢。