如何通过高级自定义字段复选框过滤自定义帖子

How filter custom posts by Advanced Custom Fields checkbox

我正在创建一个 属性 网站,主页上有一个特色 属性。为了将 属性 定义为特色,我创建了一个 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; ?>

阅读此内容:对于任何像我一样尝试使用复选框来执行此操作的人。经过一番研究后,我发现 "Checkboxes are stored as serialized data and you’re not going to be able to use WP_Query to filter by a checkbox field" 改用 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'
<?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() ): ?>
<ul>
<?php while( $query->have_posts() ) : $query->the_post();
   $images = 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 endwhile; ?>
</ul>
<?php endif; ?>

<?php wp_reset_query();  // Restore global post data stomped by the_post(). 
?>

请检查您在 acf 复选框 "Choices" 下的设置,检查它是 "Yes : Yes" 还是 "yes : Yes" 并修复您的 'meta_value' 如果您有 "yes : Yes" 'meta_value' => 'yes'。复选框将数据保存为值标签。我认为您的复选框配置有问题。

您使用哪种类型的 'images' 字段?是中继器还是画廊?如果您使用图库,那么对于您需要使用的图像的 src: $images = get_field('images'); $img_crop = $images[0]['sizes']['fresh_size'];