【问题标题】:Get list of values, then all post titles with that value获取值列表,然后获取具有该值的所有帖子标题
【发布时间】:2019-10-16 16:11:30
【问题描述】:

我有一个有效的 wordpress 循环,它显示某个 meta_query 值的所有帖子。唯一的问题是这些值是重复的。例如,如果我有两个值为“Blue”的帖子,那么两个帖子都会出现在循环中,这会使“Blue”出现两次。

我希望“蓝色”出现一次,并在其下方显示具有该值的所有帖子标题的列表。

这是我当前的查询:

<?php 
$the_query = new WP_Query(array(
    'post_type'     => 'post',
    'post_status'   => 'publish',
    'meta_key'      => 'colors',
));

while ( $the_query->have_posts() ) : $the_query->the_post(); 

$colors = get_field('colors');

if( $colors ): foreach( $colors as $color ):  
    endforeach;
    endif; 
    echo' <div><h2>'.$color.'</h2><div>'.get_the_title( $post_id ).'</div></div>';

    endwhile; wp_reset_postdata();?>

我尝试使用数组作为标题,但它只返回“数组”

$titles = get_the_title();
$title_names = array();
foreach ($titles as $title){
$title_names[] = get_the_title($id);}

回显$title_names

我在想我需要另一个带有数组的 if 语句?或者我可能是从错误的方向接近这个。

【问题讨论】:

    标签: php arrays wordpress foreach meta-query


    【解决方案1】:

    你会想尝试这样的事情:

    $results = [];
    while ( $the_query->have_posts() ) {
    
        $the_query->the_post(); 
        $colors = 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 "<div><a href=\"{$post['link']}">{$post['title']}</a></div>";
        }
    
        echo '</div>';
    }
    

    【讨论】:

    • 太棒了!正是我想要的。如果我希望这些标题是链接,例如&lt;a href="'.get_attachment_link($id).'"&gt;'.$post.'&lt;/a&gt;,我需要另一个数组,对吗?
    • 你可以像我更新答案一样使用关联数组
    • 谢谢,由于某种原因,&lt;a&gt; 出现了两次,而不是围绕标题。看起来像这样:&lt;div&gt;&lt;a href="correct-url"&gt;&lt;/a&gt;&lt;a href=""&gt;Title of Post&lt;/a&gt;&lt;div&gt;
    • 不知道为什么会这样。我需要查看您的新代码,但这是一个新问题。
    • 好的,谢谢,我会创建一个新帖子。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 2019-05-18
    相关资源
    最近更新 更多