【问题标题】:How do i show wordpress attachments from current post?如何显示当前帖子中的 wordpress 附件?
【发布时间】:2012-03-16 22:01:36
【问题描述】:
因此,在我的博客中,我有一个照片附件页面,但它一次只显示照片,而这两张照片用作导航,我讨厌这样。
我希望附件页面显示所有照片以及该组的其余部分。
这是当前代码
<div id="nav-images" class="navigation clearfix">
<div class="nav-next"><?php next_image_link() ?></div>
<div class="nav-previous"><?php previous_image_link() ?></div>
如何更改它以显示所有帖子附件?
【问题讨论】:
标签:
wordpress
thumbnails
attachment
【解决方案1】:
澄清一下,这不再有效 - 至少在 3.5.2 版本中。我改用这个;
$attachments = get_children(
array(
'post_type' => 'attachment',
'post_parent' => get_the_ID()
)
);
foreach ($attachments as $attachment) {
// ...
}
只复活一个旧帖子,因为这个帖子在这个搜索词中排名很高。
【解决方案2】:
当您在页面或帖子上时,您可以通过以下方式获取其所有附件:
global $post; // refers to the post or parent being displayed
$attachements = query_posts(
array(
'post_type' => 'attachment', // only get "attachment" type posts
'post_parent' => $post->ID, // only get attachments for current post/page
'posts_per_page' => -1 // get all attachments
)
);
foreach($attachements as $attachment){
// Do something exceedingly fancy
}
由于您当前位于附件页面,因此您可以使用 $post->post_parent 值获取所有其他附件:
global $post; // refers to the attachement object
$attachements = query_posts(
array (
'post_type' => 'attachment', // only get "attachment" type posts
'post_parent' => $post->post_parent, // attachments on the same page or post
'posts_per_page' => -1 // get all attachments
)
);
要显示附件图像,您可以使用wp_get_attachment_image_src 函数。附件的 ID 将在您的 foreach 循环的每次迭代中作为 $attachement->ID 提供(如果您使用与我的第一个示例相同的命名约定)。
【解决方案3】:
从 WordPress 3.6.0 开始,您还可以使用get_attached_media。
$media = get_attached_media( 'image', $post->ID );
if(! empty($media)){
foreach($media as $media_id => $media_file){
$thumbnail = wp_get_attachment_image_src ( $media_id, 'thumbnail' );
$full = wp_get_attachment_url( $media_id );
echo '<a href="'.$full.'" target="_blank"><img src="'.$thumbnail[0].'" alt="'.$media_file->post_title.'" /></a>';
}
}