我正在尝试建立一个缩略图列表,链接到同一类别中与其关联的单个内容页。因此,当我属于“x”类别时,列表将返回“x”类别中每个帖子的所有图像附件。
我的侧边栏中有以下代码,这些代码只包含在单个页面的内容中。但是,这只返回当前帖子图像,而不返回同一类别中的其他帖子。
我做错了什么?编辑:或者这是可能的?
<?php if ( is_single() ) { ?>
<h3><?php $category = get_the_category(); echo $category[0]->cat_name; ?></h3>
<ul class="thumbnail-navigation">
<?php while ( have_posts() ) : the_post(); ?>
<li>
<?php $size = \'thumbnail\';
$attachments = get_children( array(
\'post_parent\' => get_the_ID(),
\'post_status\' => \'inherit\',
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'order\' => \'ASC\',
\'orderby\' => \'menu_order ID\',
\'numberposts\' => -1
));
foreach ( $attachments as $thumb_id => $attachment )
?><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" ><?php echo wp_get_attachment_image($thumb_id, $size); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php } ?>
SO网友:s_ha_dum
您可以做到这一点,虽然这对服务器来说可能需要做很多工作,但这并不难。代码稍微简化了一点,应该如下所示:
$cposts = wp_list_pluck($wp_query->posts,\'ID\');
// var_dump($cposts); // debug
$args = array(
\'post_type\' => \'attachment\',
\'post_mime_type\' =>\'image\',
\'post_status\' => \'inherit\',
\'order\' => \'DESC\',
\'posts__in\' => $cposts
);
// var_dump($args); // debug
$query_images = new WP_Query( $args );
// var_dump($query_images->posts); // debug
if ($query_images->have_posts()) {
while ($query_images->have_posts()) {
$query_images->the_post(); ?>
<a href="<?php echo get_permalink($post->post_parent); ?>" title="<?php the_title_attribute(); ?>" ><?php echo wp_get_attachment_image(get_the_ID(), $size); ?></a><?php
}
}
该代码假设您在类别存档中,并使用了主查询已经返回的结果。这意味着您将只获得与分页结果的当前页面相关联的图像。
SO网友:Vimal Saifudin
<?php global $post;
$args = array(
\'posts_per_page\' => -1,
\'offset\'=> 1,
\'category\' => 9,
\'orderby\' => \'ID\',
\'order\' => \'ASC\'
);
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post );
if (has_post_thumbnail( $post->ID ) ){
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), \'single-post-thumbnail\' );
$alt_text = get_post_meta( get_post_thumbnail_id( $post->ID ), \'_wp_attachment_image_alt\', true );
$alt=\'\';
if( !empty( $alt_text )){
$alt = $alt_text;
} else {
$alt = \'\';
}
$ImageSrc = $image[0];
}
?>
<img src="<?php echo $ImageSrc; ?>" alt="<?php echo $alt; ?>" />