当循环中没有自定义帖子时添加自定义消息

Add a custom message when no custom posts in a loop

我在网站上有一个自定义 post 类型,我想在没有任何 post 类型的项目时显示一条消息。

我修改了 php 并查看了一些教程,但教程中的语法与我使用的略有不同,所以我无法完全使用它。

这是我目前所拥有的:

<section class="bigsection clearfix" id="joinus">

  <h2><?php echo(types_render_field( 'job-section-header', array( ) )); ?></h2>
  <p class="bodycopy"><?php echo(types_render_field( 'job-section-text', array( ) )); ?></p>
  <div class="jobs">
  <?php

        // WP_Query arguments
        $args = array (
            'post_type'     => array( 'job' ),
            'nopaging'      => true,
            'orderby'       => 'menu_order',
            'order'         => 'ASC'
        );

        $jobs = new WP_Query( $args );

        if ( $jobs->have_posts() ) {


            while ( $jobs->have_posts() ) {
                $jobs->the_post();
                            ?>

      <div class="single-job">
      <h3><?php the_title( ); ?></h3>
      <p><a href="<?php echo(types_render_field( 'link-to-job-description', array('output' => 'raw' ) )); ?>">Job Specification</a></p>
      </div>
  </div>
endwhile;
}
else {
            <p>There are no current vacancies at this time</p>
          }
        ?>
<?php
            }

        }

        // Restore original Post Data
        wp_reset_postdata();

        ?>

</section>

该代码在技术上显然是正确的(即没有语法错误),但是虽然它正确显示了可用的职位,但在没有任何职位可用时它没有显示 'There are no current vacancies at this time' 消息。

如有任何帮助,我们将不胜感激!

谢谢:)

你的括号太多了,你的 endwhile 前面没有 <?php 标签来让它工作。你 ".jobs" div 也需要在 if 条件下。另外最好在endwhile后面加上wp_reset_postdata();,而不是在所有条件后面,因为如果不进入if条件,就不需要使用wp_reset_postdata();。并删除所有括号,因为当你有很多 html 时,你真的不容易看到它们。

<section class="bigsection clearfix" id="joinus">

  <h2><?php echo(types_render_field( 'job-section-header', array( ) )); ?></h2>
  <p class="bodycopy"><?php echo(types_render_field( 'job-section-text', array( ) )); ?></p>
  <?php

    // WP_Query arguments
    $args = array (
        'post_type'     => array( 'job' ),
        'nopaging'      => true,
        'orderby'       => 'menu_order',
        'order'         => 'ASC'
    );

    $jobs = new WP_Query( $args );

    if ( $jobs->have_posts() ) : ?>

      <div class="jobs">
        <?php while ( $jobs->have_posts() ) : $jobs->the_post();?>

            <div class="single-job">
                <h3><?php the_title( ); ?></h3>
                <p><a href="<?php echo(types_render_field( 'link-to-job-description', array('output' => 'raw' ) )); ?>">Job Specification</a></p>
            </div>

        <?php endwhile; wp_reset_postdata();?>
      </div>
    <?php else : ?>
        <p>There are no current vacancies at this time</p>
    <?php endif; ?>


</section>