首页 > 解决方案 > 获取所有帖子中 ACF 字段的所有值以及帖子的链接

问题描述

我创建了一个 ACF 字段,我可以在其中为每个帖子添加 1 个关键字。我现在想获取我所有帖子中设置的所有关键字的列表,并按字母排序,并添加指向找到它的帖子的链接。每个关键字都是唯一的。所以这将是一种目录。我怎样才能以编程方式做到这一点?我现在不知道如何遍历帖子并获取字段值。

标签: wordpressadvanced-custom-fields

解决方案


将以下函数放在 functions.php 中。直接在您的模板中使用它或作为短代码或 w/e

function keywords_post_list() {
    //We build our query for posts containing any value in meta field
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => -1,
        'meta_query' => array(
            'key'     => 'keyword', //change with your meta key
            'value' => '',
            'compare' => '!='
        )
    );

    $query = new WP_Query($args); 
    global $post;
    $items = array();
    if($query->have_posts()): 
        while($query->have_posts()):
            $query->the_post();
            //Looping each post we collect the keyword and the link for a post.
            //Grab any other information if you need and add in the array
            $keyword = get_post_meta($post->ID,'keyword',true);
            $link = get_the_permalink($post->ID);
            //Our array
            $items[] = array('keyword'=> $keyword,'link' => $link);
        endwhile;
    endif;
    // We need to sort results by keyword currently ASC
    array_multisort(array_column($items, 'keyword'), $items);

    // If we need to sort DESC uncommnet bellow coment above
    // array_multisort(array_column($items, 'keyword'),SORT_DESC, $items);

    // error_log(print_r($items,true));

    if($items):
        echo '<ol class="keyword-list">';
        foreach($items as $item):
            $keyword = $item['keyword'];
            $link = $item['link'];
            echo '<li><a href="'.$link.'">'.$keyword.'</a></li>';
        endforeach;
        echo '</ol>';
    endif;
}

推荐阅读