我在项目中使用 ACF,我创建了一个自定义字段true/false。
有必要在一个块中显示带有字段的帖子active,而在另一个块中显示其余部分。
该代码具有以下结构:
<?php
$args = array(
'post_type' => 'client',
'post_status'=>'publish',
'posts_per_page'=>-1,
);
$the_query = new WP_Query( $args );
?>
<?php if ( get_field( 'is_active') ) : ?>
<div class="bg-gray">
<div class="container">
<h2 class="page-head_sub-title">aktive </h2>
<?php else: ?>
<div class="bg-white no-active">
<div class="container">
<h2 class="page-head_sub-title">not active</h2>
<?php endif; ?>
<div class="row equal customers-wrap">
<?php if ( have_posts() ) : ?>
<?php $e = 0; ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php
$is_active = get_field('is_active');
//var_dump($is_active);
?>
<div class="col-md-3 col-md-3 d-flex pb-3 ">
<a href="#galleryClients" class="card card-block" data-slide-to="<?php echo $e; ?>">
<?php
$thumbnail_id = get_post_thumbnail_id();
$thumbnail_url = wp_get_attachment_image_src( $thumbnail_id, 'thumbnail-size', true );
?>
<div class="item" data-toggle="modal" data-target="#clientModal">
<div class="customers-wrap_item ">
<img class="img-fluid" src="<?php echo $thumbnail_url[0]; ?>" alt="<?php the_title(); ?>" />
</div>
</div>
</a>
</div>
<?php $e++; ?>
<?php endwhile; ?>
但是这段代码没有按预期工作。很可能是因为现场检查发生在循环之外。如果您在循环内部检查,代码将起作用,但它会改变html.
如何调用检查后循环外的字段中是否存在值?
更新程序
指定id显示帖子的页面:
<?php
$args = array(
'post_type' => 'client',
'post_status'=>'publish',
'posts_per_page'=>-1,
);
$the_query = new WP_Query( $args );
?>
<?php if ( get_field( 'is_active', 289) ) : ?>
<?php
$is_active = get_field('is_active', 289);
var_dump($is_active);
?>
<div class="bg-gray">
<div class="container">
<h2 class="page-head_sub-title">active </h2>
<?php else: ?>
<div class="bg-white no-active">
<div class="container">
<h2 class="page-head_sub-title">not active</h2>
<?php endif; ?>
但var_dump($is_active);它不输出任何值,因为 在循环之外。
预期的结构html是:
如果帖子被检查为活跃
<div class="bg-gray">
<div class="container">
<h2 class="page-head_sub-title">active </h2>
<?php the_post ?>
</div>
</div>
如果帖子未被勾选为活动状态
<div class="bg-white no-active">
<div class="container">
<h2 class="page-head_sub-title">not active </h2>
<?php the_post ?>
</div>
</div>
更新 1.0
借助此代码,可以显示状态为not active的帖子:
<?php
$args = array (
'post_type' => 'client',
'post_status'=>'publish',
'posts_per_page'=>-1,
'meta_query' => array (
array (
'value' => '0'
)
)
);
$the_query = new WP_Query( $args );
?>
get_field() 函数有第二个参数 $post_id。默认情况下,这是循环中的当前帖子。在循环之外,帖子编号未定义,并且 get_field() 返回谁知道什么(很可能是空值)。在循环外,您需要像这样指定 $post_id:
您将从所需的帖子中获得必填字段的值。
if ( have_posts() )保存html结构,在循环中获取posts的is_active字段的值,还需要把while上面is_active字段的检查也移过去:要输出活动,我使用代码:
要显示not active ,我使用代码: