wordpress - 获取所有帖子中 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;
}
推荐阅读
- quantconnect - 打印问题或未定义变量
- gradle - 无论如何要覆盖 jib 的“主要”源集吗?
- macos - 如何在 SwiftUI 生命周期中显示 NSPopover?
- r - 根据数据框中另一列的最接近值查找一列的行值
- junit - 运行 testrunner.java 时出错 - junitTest
- ios - iOS 15 UITabBarController 的 tabBar 背景颜色变黑
- hdfs - 无法通过 OCI HDFS 连接器从配置单元分区表中搜索任何数据到对象存储
- discord.js - discord.js 在“guildBanAdd”事件中 dm 用户
- r - 计算个人内行之间的日期时间间隔的总和 (R)
- c# - 是否可以使用 OCR 仅提取具有特定颜色的文本?铁OCR