我在下面的循环中执行以下操作:
我遇到的问题是帖子标有多个字词,因此可能会在不同的字词中选择相同的帖子。
如何确保所选的帖子是唯一的?
<?php $terms = get_terms('project-categories', array(
'orderby' => 'rand',
'hide_empty' => 1,
)
);
shuffle($terms);
foreach ( $terms as $term ) {
if(get_field('category_on_homepage', 'project-categories_' . $term->term_id)) {
if (in_array('Yes', get_field('category_on_homepage', 'project-categories_' . $term->term_id))) {
$termid = $term->term_id;
$termname = $term->name;
$termslug = $term->slug;
$args = array(
'posts_per_page' => 1,
'orderby' => 'rand',
'post_type' => 'projects',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'project-categories',
'field' => 'id',
'terms' => $termid
)
)
);
$projects = get_posts( $args );
foreach ( $projects as $post ) {
setup_postdata($post); ?>
<a class="service" href="<?php echo $termslug; ?>">
<span class="service-image" style="background-image:url('<?php echo the_field('thumb_image'); ?>');"></span>
<span class="service-title"><?php echo $termname; ?></span>
</a>
<?php }
wp_reset_postdata();
}
}
} ?>
答案 0 :(得分:2)
构建一个使用过的帖子ID数组,然后使用post__not_in
查询参数从将来的查询中排除使用过的帖子。
<?php
$terms = get_terms('project-categories', array(
'orderby' => 'rand',
'hide_empty' => 1
)
);
$used_posts = array();
shuffle($terms);
foreach ( $terms as $term ) {
if(get_field('category_on_homepage', 'project-categories_' . $term->term_id)) {
if (in_array('Yes', get_field('category_on_homepage', 'project-categories_' . $term->term_id))) {
$termid = $term->term_id;
$termname = $term->name;
$termslug = $term->slug;
$args = array(
'posts_per_page' => 1,
'orderby' => 'rand',
'post_type' => 'projects',
'post_status' => 'publish',
'post__not_in' => $used_posts,
'tax_query' => array(
array(
'taxonomy' => 'project-categories',
'field' => 'id',
'terms' => $termid
)
)
);
$projects = get_posts( $args );
foreach ( $projects as $post ) {
setup_postdata($post);
array_push($used_posts, $post->ID);
?>
<a class="service" href="<?php echo $termslug; ?>">
<span class="service-image" style="background-image:url('<?php echo the_field('thumb_image'); ?>');"></span>
<span class="service-title"><?php echo $termname; ?></span>
</a>
<?php
}
wp_reset_postdata();
}
}
}
?>