Search code examples
phparrayswordpressforeachmeta-query

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


I have a working wordpress loop which displays all posts of a certain meta_query value. The only issue is that the values are repeated. For example, if I have two posts with the value "Blue" then both posts appear in the loop, which makes "Blue" appear twice.

What I would like is for "Blue" to appear once, and underneath it, a list of all post titles with that value.

Here's my current query:

<?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();?>

I tried using an array for the titles, but it just returned "Array"

$titles = get_the_title();
$title_names = array();
foreach ($titles as $title){
$title_names[] = get_the_title($id);}

echo $title_names

I'm thinking I need another if statement somewhere with an array? Or maybe I'm approaching this from the wrong direction.


Solution

  • You would want to try something like this:

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