如何通过“高级自定义字段"复选框过滤自定义帖子 [英] How filter custom posts by Advanced Custom Fields checkbox

查看:55
本文介绍了如何通过“高级自定义字段"复选框过滤自定义帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个财产站点,主页上有一个特色财产.要将属性定义为特色,我创建了一个acf复选框,选中该复选框时其值为Yes.我已经尝试通过检查复选框是否选中来过滤帖子,但我无法弄清楚.这是我的代码不起作用;

I am creating a property site where there is a featured property on the home page. To define a property as featured I have created an acf checkbox with the value as Yes when checked. I have tried filtering the posts by checking if the checkbox is checked but I cannot figure it out. Here's my code which isn't working;

<?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"'取决于您要实现的目标.

READ THIS: for anyone attempting to do this with a checkbox like I was don't. after a little research i found out "Checkboxes are stored as serialized data and you’re not going to be able to use WP_Query to filter by a checkbox field" Use true / false instead and check if the value equals '1' or '2' depending on what you are trying to achieve.

https://support.advancedcustomfields.com/forums/topic/using-checkbox-fields-in-custom-queries/

推荐答案

删除此部分:

'meta_key'          => 'featured_property',
'meta_value'        => 'Yes'

相反,请过滤掉循环中选中该复选框的人员.您还缺少循环的一部分.尝试以下代码:

Instead, filter out who has the checkbox checked inside the loop. You are also missing parts of the loop. Try this code:

    <?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; ?>

为了方便阅读,我已经剪掉了代码的第一部分.

I have cut out the first part of your code to make it easier to read.

-

或者,如果您想使用meta_key,请尝试添加:

Or, if you would like to use meta_key instead, try adding:

'compare' => 'EXISTS'

这篇关于如何通过“高级自定义字段"复选框过滤自定义帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆