【问题标题】:Wordpress PHP loop custom post type and display on homepageWordpress PHP循环自定义帖子类型并在主页上显示
【发布时间】:2020-07-01 13:11:44
【问题描述】:

我目前正在开发一个 WordPress 网站,并使用 CPT UI 插件创建了一个名为“事件”的自定义帖子类型。

我想在我的主页上显示事件,所以我尝试在主题文件的主页模板中创建一个循环。我一直以此为指导https://www.wpbeginner.com/wp-tutorials/how-to-create-custom-post-types-in-wordpress/

但是对于我的生活,我无法让该链接中使用的 PHP 为我工作。

<?PHP 
  $args = array( 'post_type' => 'events', 'posts_per_page' => 4 );
  $the_query = new WP_Query( $args ); 
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
  <h2><?php the_title(); ?></h2>
  <div class="entry-content">
    <?php the_content(); ?> 
  </div>
<?php wp_reset_postdata(); ?>
<?php else:  ?>
  <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

当我尝试保存时出现此错误

syntax error, unexpected 'else' (T_ELSE)

我一直在寻找这个问题的答案,但我找不到任何东西。

我对 PHP 还很陌生,如果我非常愚蠢,我很抱歉。任何帮助将不胜感激:)

【问题讨论】:

    标签: php wordpress loops


    【解决方案1】:

    你还没有结束while循环,把这段代码也放在&lt;?php endwhile; ?&gt;

    <?php 
      $args = array( 'post_type' => 'events', 'posts_per_page' => 4 );
      $the_query = new WP_Query( $args ); 
    ?>
    <?php if ( $the_query->have_posts() ) : ?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
      <h2><?php the_title(); ?></h2>
      <div class="entry-content">
        <?php the_content(); ?> 
      </div>
    <?php endwhile; ?>
    <?php wp_reset_postdata(); ?>
    <?php else:  ?>
      <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
    <?php endif; ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-23
      • 2022-07-13
      • 1970-01-01
      • 2012-11-11
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      相关资源
      最近更新 更多