首页 > 解决方案 > 如何按高级自定义字段过滤自定义帖子复选框

问题描述

我正在创建一个属性站点,其中主页上有一个特色属性。要将属性定义为特色,我创建了一个 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/

标签: phpwordpressfilteringcustom-post-typeadvanced-custom-fields

解决方案


删除这部分:

'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'

推荐阅读