我已经设法让我的循环仅显示在高级自定义字段上显示 true 的帖子。
但我现在只想显示一篇帖子。我似乎无法让它只循环其中一个以真/假字段为“是”的帖子。
'posts_per_page' => '1'
不起作用,因为它只显示最新的帖子..如果没有勾选它,它只会显示空白。
<?php
$args = array(
'post_type' => 'event'
);
$the_query = new WP_Query( $args );
?>
<?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php if ( 'yes' == get_field('sponsored_event') ): ?>
<div class="sponsored-event">
<div class="sponsored-image" style="background-image: url(<?php the_field( 'event_image' ); ?>);">
</div>
<div class="sponsored-info">
<h2>Sponsored Event</h2>
<h1><strong><?php the_title(); ?></strong></h1>
<p><strong>Date</strong></p><br>
<p class="place"><?php the_field( 'event_location' ); ?></p>
<p class="time"><?php the_field( 'event_time' ); ?></p>
<p><?php the_field( 'excerpt' ); ?></p>
</div>
</div>
<?php endif; ?>
<?php endwhile; else: ?>
<?php endif; ?>
<?php wp_reset_query(); ?>
您应该在这里使用元查询。将您的 args 数组更改为:
// args
$args = array(
'numberposts' => 1,
'post_type' => 'event',
'posts_per_page' => '1'
'meta_key' => 'sponsored_event',
'meta_value' => 'yes'
);
ACF 单选按钮“是/否”字段可以以另一种方式操作。您必须获取输出,然后与您需要的值进行比较。
语法:
$variable = get_field('field_name', $post->ID);
$post->ID 将从您使用的循环中出现。
if (get_field('sponsored_event') == 'yes') {
// code to run if the above is true
}
else
{
// code for else part
}
确保单选按钮保存到数据库中的值与您在 if 语句中给出的值相同
这是您在查询中使用meta_value 的可选选项。如果您不使用,您可以借助从
Wp_Query
循环中获得的帖子 ID 来获取 acf 值
如果您只需要将一篇文章更改为已存储的最新一篇文章,请像这样更改
Wp_Query
。
$args = array( 'post_type' => 'event', 'posts_per_page' => 1,'order'=>'DESC','orderby'=>'ID','meta_key'=> 'sponsored_event','meta_value'=>'yes');
如果您想要所有已存储的帖子,您可以像这样使用。
$args = array( 'post_type' => 'event', 'posts_per_page' => -1,'order'=>'DESC','orderby'=>'ID','meta_key'=> 'sponsored_event','meta_value'=>'yes');
注:
post_per_page=10 -> 将从您的帖子类型中带来 10 个帖子
post_per_page=-1 -> 将带来您的帖子类型拥有的无限帖子
整个循环:
<?php
$args = array(
'posts_per_page' => 1,
'post_type' => 'event',
'meta_key' => 'sponsored_event',
'meta_value' => 'yes'
);
$the_query = new WP_Query( $args );
?>
<?php if ($the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="sponsored-event">
<div class="sponsored-image" style="background-image: url(<?php the_field( 'event_image' ); ?>);">
</div>
<div class="sponsored-info">
<h2>Sponsored Event</h2>
<h1><strong><?php the_title(); ?></strong></h1>
<p><strong>Date</strong></p><br>
<p class="place"><?php the_field( 'event_location' ); ?></p>
<p class="time"><?php the_field( 'event_time' ); ?></p>
<p><?php the_field( 'excerpt' ); ?></p>
</div>
</div>
<?php endwhile; else: ?>
<?php endif; ?>
<?php wp_reset_query(); ?>
查询中的 If 语句似乎不正确,我已将查询执行输出添加到该 if 语句中。
对于那些仍然陷入困境的人。我用以下方法解决了这个问题:
$args = array(
'post_type' => 'event',
'meta_query' => array(
array(
'key' => 'sponsored_event',
'compare' => '!=',
'value' => ''
)
),
)
我认为 ACF True/False 值返回 1 和 0。不知何故,具有值 1 的查询不会返回任何内容,但会进行比较 != 并且不附加任何值,这是有效的。