I have an associative array which outputs a list of values. Under each value, there are supposed to be links to wordpress posts with that value.
These links should output as:
<a href="url">Title</a>
For some reason, they output as:
<a href="">Title</a><a href="url"></a>
It looks like the <a>
tag is being created for both title and URL.
Here's the code:
<?php
$the_query = new WP_Query(array(
'post_type' => 'post',
'post_status' => 'publish',
'meta_key' => 'colors',
));
$results = [];
while ( $the_query->have_posts() ) {
$the_query->the_post();
$credits = 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 '<a href="'.$post['link'].'">'.$post['title'].'</a>';
}
echo '</div>';
}
wp_reset_postdata();?>
A couple of tests:
foreach($posts as $post) {echo '<div><a href="">'.$post['title'].'</a></div>';}
outputs <div><a href="">Title</a></div>
but for every title, there are two blanks without the title:
<div><a href="">Title1</a></div>
<div><a href=""></a></div>
<div><a href=""></a></div>
<div><a href="">Title2</a></div>
<div><a href=""></a></div>
<div><a href=""></a></div>
Similarly, foreach($posts as $post) { echo '<div>'.$post['link'].''.$post['title'].'</div>';}
is creating blank containers:
<div>Title1</div>
<div>URL1</div>
<div></div>
<div>Title2</div>
<div>URL2</div>
<div></div>
Here is the problem:
You are using [] for the same array 2 times. And this splits color-link couple from each other. They are saved into different array. Use defined indexes instead
or you can simply do it with single line