php - 如何按高级自定义字段过滤自定义帖子复选框
问题描述
我正在创建一个属性站点,其中主页上有一个特色属性。要将属性定义为特色,我创建了一个 acf 复选框,选中时值为 Yes。我尝试通过检查复选框是否被选中来过滤帖子,但我无法弄清楚。这是我的代码不起作用;
<?php
$args = array(
'post_type' => 'property',
'posts_per_page' => 1,
'meta_key' => 'featured_property',
'meta_value' => 'Yes'
);
$query = new WP_Query( $args );
?>
<?php if( $query->have_posts() ) : ?>
<?php
$main_field = get_field('images');
$first_row = $main_field[0];
$img = $first_row['image'];
$img_crop = $img['sizes']['fresh_size'];
?>
<img src="<?php echo $img_crop; ?>" alt="featuredproperty" class="img-fluid">
<?php wp_reset_postdata(); ?>
<?php endif; ?>
阅读此内容:对于任何尝试使用复选框来执行此操作的人,就像我没有的那样。经过一番研究,我发现“复选框存储为序列化数据,您将无法使用 WP_Query 按复选框字段进行过滤”改为使用 true / false 并检查值是否等于 '1' 或 '2 ' 取决于您要达到的目标。
https://support.advancedcustomfields.com/forums/topic/using-checkbox-fields-in-custom-queries/
解决方案
删除这部分:
'meta_key' => 'featured_property',
'meta_value' => 'Yes'
相反,过滤掉谁在循环内选中了复选框。您还缺少循环的部分内容。试试这个代码:
<?php if( $query->have_posts() ) : ?>
(...)
<!-- start of the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php if( get_field('featured_property') ) { // << FROM HERE ?>
<img src="<?php echo $img_crop; ?>" alt="featuredproperty" class="img-fluid">
<?php } // << TO HERE ?>
<?php endwhile; ?><!-- end of the loop -->
<?php wp_reset_postdata(); ?>
<?php endif; ?>
我已经剪掉了你的代码的第一部分,以便于阅读。
--
或者,如果您想改用 meta_key,请尝试添加:
'compare' => 'EXISTS'
推荐阅读
- django - 如何自动生成带参数的django rest框架文档?
- cookies - 使用信用卡付款后跟踪 cookie
- node.js - Electron.js:获取已安装的应用程序并打开它们
- uno-platform - Uno 平台初始化材质
- python - 有没有办法使用 selenium 控制权限弹出窗口(通知权限)
- reactjs - useState 在带有材料 ui 抽屉的下一个 js 中不起作用
- nestjs - NestJS 中的异常过滤器不会捕获带有错误 json 正文的错误请求
- python - 在 Python 列表中合并字典
- google-sheets - 结合公式以从列中的定界值中获取唯一列表与公式以获取范围连接工作表名称以输出
- chainlink - 在结构 Chainlink.Request 内存中进行参数相关查找后,成员“添加”未找到或不可见