获取值列表,然后获取所有 post 个具有该值的标题

Get list of values, then all post titles with that value

我有一个工作的 wordpress 循环,它显示某个 meta_query 值的所有 post。唯一的问题是值是重复的。例如,如果我有两个值为 "Blue" 的 post,那么两个 post 都会出现在循环中,这使得 "Blue" 出现两次。

我希望 "Blue" 出现一次,并在其下方列出具有该值的所有 post 标题。

这是我当前的查询:

<?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 语句吗?或者也许我从错误的方向接近这个。

你会想尝试这样的事情:

$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>';
}