我有一个工作的wordpress循环,它显示某个meta_query
值的所有帖子。唯一的问题是重复这些值。例如,如果我有两个值为“ Blue”的帖子,则两个帖子都出现在循环中,这会使“ Blue”出现两次。
我希望“蓝色”出现一次,并在其下方列出具有该值的所有帖子标题。
这是我当前的查询:
<?php
$the_query = new WP_Query(array(
'post_type' => 'post',
'post_status' => 'publish',
'meta_key' => 'colors',
));
while ( $the_query->have_posts() ) : $the_query->the_post();
$colors = get_field('colors');
if( $colors ): foreach( $colors as $color ):
endforeach;
endif;
echo' <div><h2>'.$color.'</h2><div>'.get_the_title( $post_id ).'</div></div>';
endwhile; wp_reset_postdata();?>
我尝试使用标题数组,但它只返回了“ Array”
$titles = get_the_title();
$title_names = array();
foreach ($titles as $title){
$title_names[] = get_the_title($id);}
回声$title_names
我在想我是否需要另一个if语句和数组?也许我是从错误的方向来解决这个问题。
答案 0 :(得分:1)
您想尝试这样的事情:
$results = [];
while ( $the_query->have_posts() ) {
$the_query->the_post();
$colors = get_field('colors');
if( !empty($colors) ) {
foreach( $colors as $color ) {
$results [$color][]['title'] = get_the_title();
$results [$color][]['link'] = get_attachment_link();
}
}
}
foreach ($results as $color => $posts) {
echo "<div><h2>{$color}<h2>";
foreach($posts as $post) {
echo "<div><a href=\"{$post['link']}">{$post['title']}</a></div>";
}
echo '</div>';
}