Php 如果不存在帖子,则隐藏循环
我只是有一个通过CPT的循环,但是我想隐藏循环的整个容器div,如果它没有POST 我正在尝试围绕容器的if语句的各种迭代:Php 如果不存在帖子,则隐藏循环,php,wordpress,loops,hide,Php,Wordpress,Loops,Hide,我只是有一个通过CPT的循环,但是我想隐藏循环的整个容器div,如果它没有POST 我正在尝试围绕容器的if语句的各种迭代: <?php if( have_posts() ): ?> <?php endif; ?> 但我似乎无法让它正常工作。。。完整的代码博客在这里: <?php if( have_posts() ): ?> <div class="container default-strip-section"> &l
<?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不为true时,不会显示整个容器。
但您使用的是职位的ACF字段,在该字段中显示此空缺列表。因此,我们将id保存到一个变量中,以便能够查看名为the\u 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的答案几乎是正确的——它需要对象实例,然后再发布()
<?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();
?>
感谢您的排名,并解释了一些重新编写的方法:)但是,当我添加代码时,它似乎会破坏页面-似乎只是不停地一次又一次地吐出来。。。我不知道如何解决这个问题:-/我不知道你把代码放在哪里了。我删除了外部if子句,请再次检查代码。我想你是把这个代码放在一个单独的帖子页面里?那么职位中是否设置了ACF字段(空缺职位)?职位空缺是否与职位有关,所以你需要这个特定的h2?请告诉我一些,这样我可以帮你:)我想我不需要包含外部if子句?-我刚刚用你的新代码替换了整个东西,所以它就这样放在一个普通的页面模板中。。。但是它一直在循环,最终使我的浏览器崩溃(浏览器停止了它,因为它使用了大量的数据)…哦,我也没有把它放在一个单独的帖子页面上,它放在一个普通的模板页面上…自定义的帖子类型操作系统没有分类。我正在将自定义文件附加到职业页面模板。。。职位名称仅使用职位名称。职位CPT中没有ACF。。。所以应该显示瓦坎卡的标题谢谢你,鞋带!我明白现在缺少什么:)