如果不存在帖子则隐藏循环

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放在ifhave_posts()之后,检查是否有post。这样,当 if 不为真时,不会显示整个容器。 但是您正在使用 post 的 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() 之前的对象实例:

<?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();
?>