数组会创建重复的标签(wordpress)

时间:2019-06-01 05:54:48

标签: php wordpress foreach associative-array

我有一个关联数组,可以输出值列表。在每个值下,应该有指向具有该值的wordpress帖子的链接。

这些链接应输出为: <a href="url">Title</a>

由于某种原因,它们输出为: <a href="">Title</a><a href="url"></a>

似乎为标题和URL都创建了<a>标签。

代码如下:

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

一些测试:

foreach($posts as $post) {echo '<div><a href="">'.$post['title'].'</a></div>';}

输出<div><a href="">Title</a></div>,但对于每个标题,有两个没有标题的空格:

<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>

类似地,foreach($posts as $post) { echo '<div>'.$post['link'].''.$post['title'].'</div>';}正在创建空白容器:

<div>Title1</div>
<div>URL1</div>
<div></div>
<div>Title2</div>
<div>URL2</div>
<div></div>

1 个答案:

答案 0 :(得分:2)

问题出在这里

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

您将[]用于同一数组2次。并且这将颜色链接对彼此分开。它们被保存到不同的数组中。改用已定义的索引

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

或者您也可以只用一行来完成

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