Array creates duplicate tags (wordpress)

2019-07-26 23:39发布

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>

1条回答
Rolldiameter
2楼-- · 2019-07-27 00:03

Here is the problem:

 foreach( $colors as $color ) {  
            $results [$color][]['title'] = get_the_title();
            $results [$color][]['link'] = get_attachment_link();
        }

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

 $i=0;
 foreach( $colors as $color ) {  
             $results [$color][$i]['title'] = get_the_title();
             $results [$color][$i]['link'] = get_attachment_link();
             $i++;            
        }

or you can simply do it with single line

foreach( $colors as $color ) {  
           $results [$color][]=array('title' => get_the_title(),
           'link' => get_attachment_link());
       }
查看更多
登录 后发表回答