如何解决使用get_posts获取ACF Relationship关联字段值失败问题
问题原因分析
- 关联字段存储位置错误:你将
related_item关联字段添加在publication自定义文章类型下,该字段值仅存储在publication类型文章的元数据中,你当前查询post_type设置为item,相当于在item类型的元数据中检索不存在的字段,自然无法返回结果。 - 查询方向完全倒置:你当前的写法是从item出发反向查询关联它的publication的逻辑,和你要实现的「从publication出发查询关联的item」需求完全相反。
正确实现方案
方案1:直接读取关联字段值(最简便,适用于ACF等主流自定义字段工具)
如果你的关联字段是通过ACF等工具创建的,无需额外写查询,直接读取当前publication的关联字段即可拿到关联的item对象数组:
// 直接获取当前publication关联的所有item $related_items = get_field('related_item');
方案2:使用get_posts实现查询
如果你需要手动写查询实现,先读取当前publication存储的关联item ID列表,再通过ID批量查询item:
// 获取当前publication关联的item ID数组 $related_item_ids = get_post_meta( get_the_ID(), 'related_item', true ); $related_items = []; if ( !empty($related_item_ids) ) { $related_items = get_posts( [ 'post_type' => 'item', 'post__in' => $related_item_ids, 'posts_per_page' => -1, ] ); }
附加:获取item的颜色代码
拿到关联的item列表后,循环读取color picker字段值即可:
if ( !empty($related_items) ) { foreach ( $related_items as $single_item ) { // 将下方的color_field_name替换为你实际的color picker字段名 $color_code = get_post_meta( $single_item->ID, 'color_field_name', true ); // 此处编写颜色代码的后续业务逻辑 } // 重置文章全局变量,避免污染后续查询 wp_reset_postdata(); }
反向查询的补充说明
如果你确实需要实现「查询某个item被哪些publication关联」的反向需求,才需要使用你原有的LIKE查询逻辑,只需将查询的post_type改为publication即可:
$related_publications = get_posts( [ 'post_type' => 'publication', 'meta_query' => [ [ 'key' => 'related_item', 'value' => '"' . get_the_ID() . '"', 'compare' => 'LIKE' ] ] ] );
如果你的关联字段设置为仅存储单个ID而非序列化数组,可将compare改为=,去掉value两侧的引号
内容的提问来源于stack exchange,提问作者designmode
相关产品推荐
相关产品推荐

