数组创建重复标签(wordpress) [英] Array creates duplicate tags (wordpress)
问题描述
我有一个输出值列表的关联数组.在每个值下,应该有指向具有该值的wordpress帖子的链接.
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.
这些链接应输出为:
<a href="url">Title</a>
These links should output as:
<a href="url">Title</a>
由于某种原因,它们输出为:
<a href="">Title</a><a href="url"></a>
For some reason, they output as:
<a href="">Title</a><a href="url"></a>
似乎为标题和URL创建了<a>
标签.
It looks like the <a>
tag is being created for both title and URL.
代码如下:
<?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>
,但是对于每个标题,有两个没有标题的空格:
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>
类似地,foreach($posts as $post) { echo '<div>'.$post['link'].''.$post['title'].'</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>
推荐答案
问题出在这里:
foreach( $colors as $color ) {
$results [$color][]['title'] = get_the_title();
$results [$color][]['link'] = get_attachment_link();
}
您将[]用于同一数组2次.并且这将颜色链接对彼此分开.它们被保存到不同的数组中.改用已定义的索引
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());
}
这篇关于数组创建重复标签(wordpress)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!