gpt4 book ai didi

php - 在自定义帖子类型中使用 ACF 复选框字段来过滤不同自定义帖子类型的结果

转载 作者:搜寻专家 更新时间:2023-10-31 21:47:12 25 4
gpt4 key购买 nike

我有一个正在循环的页面(自定义帖子类型 1)。嵌套在(自定义帖子类型 1)中我有另一个循环(自定义帖子类型 2)。目标是在(自定义帖子类型 1)中勾选 ACF 复选框,根据 checkin 的内容(自定义帖子类型 1)过滤(自定义帖子类型 2)的结果。

我是 StackOverflow 和 Wordpress 开发的新手。但我让它按照我上面描述的方式工作,但有一个回退。您必须在(自定义帖子类型 2)中提供可用的复选框,$meta_query 才能工作。完全有道理为什么在阅读文档之后以及我如何进行此设置。

我将如何做到这一点(自定义帖子类型 2)不需要复选框来根据(自定义帖子类型 1)选中的复选框进行过滤?

<?php
// Custom Post Type 1
$args1 = array(
'post_type' => 'custom_post_type_1',
'posts_per_page' => -1,
);
$custom_post_type_1 = get_posts( $args1 );

foreach( $custom_post_type_1 as $post ) : setup_postdata( $post );
// Do things

// Get the selected options from custom post type 1 and throw them into an array
$my_acf_checkbox = get_field('checkbox', $post->ID);
$meta_query = array('relation' => 'OR');
foreach( $my_acf_checkbox as $item ){
$meta_query[] = array(
'key' => 'checkbox',
'value' => $item,
'compare' => 'LIKE',
);
}

// Custom Post Type 2 (Nested)
$args2 = array(
'post_type' => 'custom_post_type_2',
'posts_per_page' => -1,
'meta_query' => $meta_query
);
$custom_post_type_2 = get_posts( $args2 );

foreach( $custom_post_type_2 as $post ) : setup_postdata( $post );
// Do things
wp_reset_postdata();
endforeach;

wp_reset_postdata();
endforeach;
?>

最佳答案

我很好奇您为什么要使用复选框 ACF 字段?返回的值是什么?发布 ID,鼻涕虫?我通常会使用 Post Object 字段并返回一个 ID,因此它比将值硬编码到复选框字段中更具动态性。

我假设您在下面的解决方案的复选框中返回了 post_ids。

我可以看到你正在尝试使用 meta_query 做什么,但如果你有 ID,你可以简单地在你的 $args2 中使用 post__in 进行第二个循环,而不是这样:

$my_acf_checkbox = get_field('checkbox', $post->ID);
$meta_query = array('relation' => 'OR');
foreach( $my_acf_checkbox as $item ){
$meta_query[] = array(
'key' => 'checkbox',
'value' => $item,
'compare' => 'LIKE',
);
}

只需像这样将您的 id 单独放入一个数组中:

foreach( $my_acf_checkbox as $item ){
$cpt2s[] = $item;
}

然后在 post__in $args2 中使用你的新数组:

$args2 = array(                                      
'post_type' => 'custom_post_type_2',
'posts_per_page' => -1,
'post__in' => $cpt2s
);

让我知道这是否可以作为您的解决方案,或者是否有任何不合理的地方。

关于php - 在自定义帖子类型中使用 ACF 复选框字段来过滤不同自定义帖子类型的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56877502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com