[英]Hide loop if no posts exist
我只是有一个循环通过 CPT,但我想隐藏循环的整个容器 div,如果它没有帖子...
我正在尝试围绕容器的 if 语句的各种迭代:
<?php if( have_posts() ): ?>
<?php endif; ?>
但我似乎无法让它正常工作......完整的代码博客在这里:
<?php if( have_posts() ): ?>
<div class="container default-strip-section">
<h2><?php the_field('vacancies_title'); ?></h2>
<div class="row justify-content-center">
<?php
$args = array(
'post_type' => 'vacancies',
'posts_per_page' => 9999
// 'orderby' => 'title',
// 'order' => 'ASC'
);
$the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="col-md-12">
<a href="<?php the_permalink(); ?>">
<p><?php the_title() ?></p>
</a>
</div>
<?php endwhile; wp_reset_postdata(); endif; ?>
</div>
</div>
<?php endif; ?>
谁能指出我做错了什么? 我确定我错过了一些简单的东西:感谢您的关注!! :)
您需要将容器的 html 放在 if have_posts()
之后,检查是否有任何帖子。 这样,当 if 不为真时,不会显示整个容器。 但是您正在使用显示此职位空缺列表的帖子的 ACF 字段。 因此,我们将 id 保存到一个变量中,以便能够查看名为the_query
的自定义查询中的值(这不是一个不言自明的/好名字)。 为什么不将其称为vacancies_query
以获得更易读的代码。 放在一起应该是这样的:
<?php
$current_post = get_the_ID();
$args = array(
'post_type' => 'vacancies',
'posts_per_page' => 9999
);
$vacancies_query = new WP_Query( $args );
if ( $vacancies_query->have_posts() ) : ?>
<div class="container default-strip-section">
<h2><?php the_field('vacancies_title', $current_post); ?></h2>
<div class="row justify-content-center">
<?php while ( $vacancies_query->have_posts() ) : the_post(); ?>
<div class="col-md-12">
<a href="<?php the_permalink(); ?>">
<p><?php the_title() ?></p>
</a>
</div>
<?php endwhile; ?>
</div> <!-- row -->
</div> <!-- container -->
<?php else :
/* nothing to see here */
endif;
wp_reset_postdata();
?>
@rank 的答案几乎是正确的——在the_post()
之前它需要 object 实例:
<?php
$args = array(
'post_type' => 'vacancies',
'posts_per_page' => 9999, // If you're wanting to show all posts, use -1 here.
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
?>
<div class="container default-strip-section">
<h2><?php the_field('vacancies_title'); ?></h2>
<div class="row justify-content-center">
<?php
while ( $the_query->have_posts() ) :
$the_query->the_post();
?>
<div class="col-md-12">
<p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
</div>
<?php
endwhile;
?>
</div>
</div>
<?php
endif;
wp_reset_postdata();
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.