我正在创建一个属性站点,主页上有一个特色属性。要将属性定义为特征,我创建了一个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'
<?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”下检查您的设置,检查它是“是:是”还是“是:是”并修复您的'meta_value'如果您对'meta_value'=>'是'有“是:是”。复选框将数据保存为值标签。我认为你的复选框配置有问题。
您使用什么类型的“图像”字段?是转发器还是画廊?如果你使用gallery然后你需要使用图像的src:$ images = get_field('images'); $ img_crop = $ images [0] ['sizes'] ['fresh_size'];