【问题标题】:Array creates duplicate tags (wordpress)数组创建重复标签(wordpress)
【发布时间】:2019-10-17 15:25:50
【问题描述】:

我有一个关联数组,它输出一个值列表。在每个值下,应该有指向具有该值的 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 '&lt;div&gt;&lt;a href=""&gt;'.$post['title'].'&lt;/a&gt;&lt;/div&gt;';}

输出&lt;div&gt;&lt;a href=""&gt;Title&lt;/a&gt;&lt;/div&gt;,但对于每个标题,有两个空白没有标题:

<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 '&lt;div&gt;'.$post['link'].''.$post['title'].'&lt;/div&gt;';} 正在创建空白容器:

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

【问题讨论】:

  • 输出为&lt;div&gt;&lt;h2&gt;Color&lt;/h2&gt;--Title&lt;/div&gt;,所以只是来自该部分的--Title
  • &lt;div&gt;--Title&lt;/div&gt; 我只注释掉了echo '&lt;div&gt;&lt;h2&gt;'.$color.'&lt;/h2&gt;';,然后又注释掉了echo '&lt;/div&gt;';。同样的事情。
  • 抱歉,这只是页面内容的包装元素。你可以无视。它来自循环外的 html。
  • 我仍然无法看到echo $post['link'].'--'.$post['title'];die; 的真正价值。在我看到之前我无能为力。似乎两者都只给你链接
  • 好吧,你说的实际价值是什么意思?另外,我运行了两个测试(上面编辑),我可以根据 html 元素 的数量来判断是否引入了空白容器

标签: php wordpress foreach associative-array


【解决方案1】:

问题来了:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    相关资源
    最近更新 更多