获取所有文章中某个ACF字段的所有值以及这些文章的链接



我已经创建了一个ACF字段,我可以在每个帖子中添加1个关键字。我想现在得到的所有关键字设置在我的所有帖子的列表,并按字母排序,并添加一个链接到帖子,它被发现的地方。每个关键字都是唯一的。这是一种目录。我怎么用程序来做呢?我现在不知道如何循环通过帖子和获取字段值。

将以下函数放入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;
}

最新更新