循环代码正在显示页面,但不显示实际的帖子

时间:2016-03-13 作者:iliketolearn

此代码仅返回我构建的自定义页面的名称-主页。为什么返回页面标题?我想显示帖子。

 <?php
     if ( have_posts() ) {
     while ( have_posts() ) {

    the_post(); ?>

    <h2><?php the_title(); ?></h2>

    <?php the_content(); ?>

<?php }
 }
 ?>

1 个回复
最合适的回答,由SO网友:frogg3862 整理而成

评论中的解释:

<?php
/* This is your original loop (`have_posts`). Even on a custom template, the first loop references
the PAGE to which your template is-- this being your homepage. In order to display posts,
you must use a new query, as in the next chunk of code. */

if ( have_posts() ) {
    while ( have_posts() ) {
        the_post(); ?>
        <h2><?php the_title(); ?></h2>
        <?php the_content(); ?>

<?php
    }
}
?>
以下是如何获取帖子:

/* You can replace your original loop with the code below. This will query 10 posts
and return their titles.
See http://codex.wordpress.org/Class_Reference/WP_Query for customizing it. */

$args = array(
    \'post_type\'         => \'post\',
    \'posts_per_page\'    => 10
);
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    echo \'<ul>\';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo \'<li>\' . get_the_title() . \'</li>\';
    }
    echo \'</ul>\';
}
/* Restore original Post Data */
wp_reset_postdata();

相关推荐

当in_the_loop()为假时,何时以及为什么is_Single(‘my_cpt’)为真?

我正在使用模板系统的示例代码。此地址的页码:http://project.test/my_cpt/hello-post/.无法理解原因is_singular( \'my_cpt\' ) 是true 虽然in_the_loop() 是false.在页面模板中The Loop "E;“工程”:if ( have_posts() ) { while ( have_posts() ) { the_post(); ?>