无法遍历自定义帖子类型

时间:2019-03-25 19:07:49

标签: php wordpress

我有一个名为external_press的自定义帖子类型,当我尝试遍历并显示the_title()时,我得到的只是帖子的标题。我正在使用index.php文件。

这是我的自定义帖子类型注册:

function custom_post_type_init() {
  register_post_type( 'external_press',
    array(
      'labels' => array(
        'name' => __( 'External Press' ),
        'singular_name' => __( 'Press' )
      ),
      'public' => false,  // it's not public, it shouldn't have it's own permalink, and so on
      'publicly_queryable' => true,  // you should be able to query it
      'show_ui' => true,  // you should be able to edit it in wp-admin
      'exclude_from_search' => true,  // you should exclude it from search results
      'show_in_nav_menus' => false,  // you shouldn't be able to add it to menus
      'has_archive' => false,  // it shouldn't have archive page
      'rewrite' => false,  // it shouldn't have rewrite rules
      'menu_position' => 5, // bellow posts
      // 'supports' => array( // only show title and thumnail
      //   'title',
      //   'thumbnail'
      // ),
    )
  );
}
add_action( 'init', 'custom_post_type_init' );

这是我尝试显示自定义帖子类型标题的方式

$args = new WP_Query(array(
            'post_type' => 'external_press',
        ));

        // the query
        $the_query = new WP_Query( $args ); ?>

        <?php if ( $the_query->have_posts() ) : ?>

            <!-- pagination here -->

            <!-- the loop -->
            <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
                <h2><?php the_title(); ?></h2>
            <?php endwhile; ?>
            <!-- end of the loop -->

            <!-- pagination here -->

            <?php wp_reset_postdata(); ?>

        <?php else : ?>
            <p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
        <?php endif; ?>

1 个答案:

答案 0 :(得分:1)

您要两次声明WP_Query。

请参见下面的循环示例。

<?php $loop = new WP_Query( array( 'post_type' => 'external_press' ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
        <h2><?php the_title(); ?></h2>
<?php endwhile; wp_reset_query(); ?>

在此处查看更多信息: https://codex.wordpress.org/Post_Types#Querying_by_Post_Type