【问题标题】:WordPress - 'The Loop' to show all posts, instead posts the title of the home pageWordPress - 'The Loop' 显示所有帖子,而不是发布主页的标题
【发布时间】:2017-05-06 15:02:37
【问题描述】:

我刚开始使用 wordpress 教程系列,它做的第一件事就是制作一个简单的“循环”,打印所有帖子的标题和描述。但是,当我这样做时,它会打印主页的名称和描述。

<?php 
if ( have_posts() ) 
 {
  while ( have_posts() ) 
    {
        the_post(); 
        the_title('<h2><a href="the_permalink();"','</a></h2>');   
        the_content(); 
        // Post Content here
        //
    } // end while
 } // end if
?>

我无法弄清楚为什么它打印主页信息而不是发布信息。

【问题讨论】:

  • 你把代码放在哪里了?如果你想显示所有帖子的标题和内容,你应该考虑全局变量$post。
  • 这是整个索引文件。我正在关注一个视频教程,他们能够使用它。

标签: php wordpress


【解决方案1】:

要在任何页面上显示 wordpress 帖子,您需要在 WP_Query 中传递如下参数,然后通过对象循环它们。

// The Query
$the_query = new WP_Query( array( 'post_type' => 'post','posts_per_page' => -1 ) );

// 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();
} else {
    // no posts found
}

【讨论】:

  • 好吧,这更有意义。我想知道 the_post 从哪里得到它的信息。我只是有点困惑,因为我正在关注一个不需要制作新对象的视频教程。
  • 其实the_post默认会先获取首页(一般是你的首页)信息。如果您想在主页上显示您的帖子,那么您可以通过将设置面板中的阅读选项更改为博客来实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 2014-12-28
  • 1970-01-01
  • 2018-10-12
  • 2012-10-02
  • 2012-07-29
相关资源
最近更新 更多