好的,我会再详细一点。我用这个代码得到了一个按字母排序的艺术家列表。在这个列表中,我展示了这个艺术家术语对应的所有新闻帖子。功能正常。但是,如果有一条新闻与不止一位艺术家对应,那么我会在与该帖子对应的每一位艺术家下面得到相同的帖子。我想做的是为第一位与这篇文章相对应的艺术家展示这篇文章/新闻。而不是为列表中的每个艺术家多次显示帖子。显示的代码用于列出艺术家并显示下面相应的帖子。提前感谢,并对之前不可靠的描述表示抱歉。
<?php foreach ( $artist_terms as $artist_term ): ?>
<?php $news = get_posts(array (
\'numberposts\' => 0,
\'order\' => \'DESC\',
\'meta_key\' => \'date\',
\'value\' => \'date(yyyy-mm-dd)\',
\'orderby\' => \'meta_value\',
\'post_type\' => \'news\',
\'artist\' => $artist_term->slug
));
?>
<? if($news): ?>
<li>
<?php foreach ($news as $post) : ?>
<div>
<?php the_post_thumbnail();?>
<?php $artist_name = strip_tags (get_the_term_list( get_the_ID(), \'artist\')); echo $artist_name; ?>
</div>
<?php endforeach; ?>
</li>
<?php endif; ?>
<?php endforeach; ?>
这个代码的替代品我找到了这个
http://wordimpress.com/loop-through-categories-and-display-posts-within/. 这也是一样的,但对于重复项也没有解决方案。
<?php
/*
* Loop through Categories and Display Posts within
*/
$post_type = \'news\';
// Get all the taxonomies for this post type
$taxonomies = get_object_taxonomies( array( \'post_type\' => $post_type ) );
foreach( $taxonomies as $taxonomy ) :
// Gets every "category" (term) in this taxonomy to get the respective posts
$terms = get_terms( $taxonomy );
foreach( $terms as $term ) : ?>
<?php// echo $term->name; ?>
<?php $ids = array();
$ids[] = get_the_ID();
?>
<?php
$args = array(
\'post_type\' => $post_type,
\'posts_per_page\' => -1, //show all posts
\'tax_query\' => array(
array(
\'taxonomy\' => $taxonomy,
\'field\' => \'slug\',
\'terms\' => $term->slug,
\'post__not_in\' => $ids
)
)
);
$posts = new WP_Query($args);
if( $posts->have_posts() ): while( $posts->have_posts() ) : $posts->the_post(); ?>
<?php
$args2 = array(
\'post_type\' => $post_type,
\'posts_per_page\' => -1, //show all posts
\'tax_query\' => array(
array(
\'taxonomy\' => $taxonomy,
\'field\' => \'slug\',
\'terms\' => $term->slug,
\'post__not_in\' => $ids
)
)
);
$posts2 = new WP_Query($args2); ?>
<?php if(has_post_thumbnail()) { ?>
<?php the_post_thumbnail(); ?>
<br>
<?php }
/* no post image so show a default img */
else { ?>
<img src="<?php bloginfo(\'template_url\'); ?>/assets/img/default-img.png" alt="<?php echo get_the_title(); ?>" title="<?php echo get_the_title(); ?>" width="110" height="110" />
<?php } ?>
<br>
<?php echo get_the_title(); ?>
<br><br><br>
<?php endwhile; endif; ?>
<?php endforeach;
endforeach; ?>