[英]wordpress handle ACF custom fields of type relationship with WP_Query
我在其中一个函数中使用了WP_Query。
function get_id_list ($postType) {
$wpb_all_query = new WP_Query(
array(
'post_type' => $postType,
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
array(
//'key' => 'title',
//'value' => 'Wordpress Development BSP Project', // this works and the function only returns a list with the single ID of the post where this matches
'key' => 'bicslab_axis',
'value' => '22', // this does not work
'value' => 'greenware', // this does not work
)
)
)
);
$postIDList = [];
if($wpb_all_query->have_posts()){
while ( $wpb_all_query->have_posts() ) {
$wpb_all_query->the_post();
$postIDList[] = get_the_ID();
}
wp_reset_postdata();
}
print_r($postIDList);
return $postIDList;
}
当我在'meta_query'
选择一个键为“文本”类型的字段时,查询正常工作,但是如果选择“关系”类型的字段,则查询不正确。
对于关系字段,我尝试输入ID和名称,但它们都不起作用。
如何使查询仅检索类型关联的自定义字段仅与某些对象相关的帖子?
编辑:我应该澄清一下,我在"22"
mea”查询中分别使用"22"
和"greenware"
作为值,因为22是ID,而greenware是具有该ID的特定博客文章/对象的“名称”
这是因为您要在object
搜索string
。
使用WP_Query参数
可以仅加载选定的帖子ID,而不是帖子对象。 这样,您可以在WP_Query中使用ID并指定参数,例如posts_per_page,order和orderby。 要了解有关WP_Query参数的更多信息,请阅读http://codex.wordpress.org/Class_Reference/WP_Query#Parameters 。
请注意,get_field函数具有2个错误参数。 第一个参数用于$ post_id,并且不相关,但是第二个参数是告诉ACF不要格式化该值,并且仅返回数据库中的内容(ID数组)
<?php
// get only first 3 results
$ids = get_field('conference_talks', false, false);
$query = new WP_Query(array(
'post_type' => 'conferences',
'posts_per_page' => 3,
'post__in' => $ids,
'post_status' => 'any',
'orderby' => 'post__in',
));
?>
资料来源: https : //www.advancedcustomfields.com/resources/relationship/
我找到了解决方案: ACF的WordPress查询帖子
我唯一需要更改的是'value'
和'compare'
参数,其内容如下:
'value' =>'22',
'compare' => '=',
对此:
'value' =>'"'.'22'.'"',
'compare' => 'LIKE',
编辑:它甚至可以在不带引号的情况下工作:
'value' => '22',
'compare' => 'LIKE',
这是完整的代码:
function get_id_list ($postType) {
$wpb_all_query = new WP_Query(
array(
'post_type' => $postType,
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'bicslab_axis',
'value' => '22',
'compare' => 'LIKE',
)
)
)
);
$postIDList = [];
if($wpb_all_query->have_posts()){
while ( $wpb_all_query->have_posts() ) {
$wpb_all_query->the_post();
$postIDList[] = get_the_ID();
}
wp_reset_postdata();
}
print_r($postIDList);
return $postIDList;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.