【问题标题】:Can't seem to end loop in wordpress page template似乎无法在 wordpress 页面模板中结束循环
【发布时间】:2016-11-23 23:10:51
【问题描述】:

完全披露,我是 PHP 菜鸟。 我在尝试为我的 Wordpress 网站构建的页面模板时遇到问题。我们的想法是显示今天的每个帖子,并排除所有其他帖子。

有人帮我编写了一些代码,但我遇到了一个新问题 - 仅显示今天最旧的帖子!我测试了三个间隔几分钟的帖子,只有第一个出现。

任何帮助表示赞赏。

完整代码如下。

<?php
/**
 * Template Name: Home Page
 * The template for displaying all of today's posts on home page.
 *
 * This is the template that displays only today's posts.
 * Please note that this is the WordPress construct of pages and that
 * other "pages" on your WordPress site will use a different template.
 *
 * @package WordPress
 * @subpackage Twenty_Fifteen
 * @since Twenty Fifteen 1.0
 */

get_header(); ?>

<?php
$today = getdate();
$args = array(
    'date_query' => array(
        array(
            'year' => $today['year'],
            'month' => $today['mon'],
            'day' => $today['mday'],
        ),
    ),
);
$query = new WP_Query( $args );
?>


<div id="primary" class="content-area">
    <main id="main" class="site-main" role="main">

    <?php
    // Start the loop.
    if ($query->have_posts() )
        echo'<ul>';
        while ( $query->have_posts() ) {
            $query->the_post();
        }
        echo '</ul>';

        // Include the page content template.
        get_template_part( 'content', 'page' );

            // If comments are open or we have at least one comment, load up the comment template.
            if ( comments_open() || get_comments_number() ) :
                comments_template();

        /* Restore Post Data */
        wp_reset_postdata();
        else : // no posts found. 
        ;

    endif ;
    ?>

    </main><!-- .site-main -->
</div><!-- .content-area -->

<?php get_footer(); ?>

【问题讨论】:

  • 从管理员设置每页的帖子到 -1
  • 我假设您的意思是阅读设置。它不允许我使用小于 0 的任何东西。
  • 然后归零,你面临的问题其实是分页
  • 哎呀,我的意思是小于 1。我的错。

标签: php wordpress loops posts


【解决方案1】:
$args = array(
    'date_query' => array(
        array(
            'year' => $today['year'],
            'month' => $today['mon'],
            'day' => $today['mday'],
        ),
    ),
    'posts_per_page' => -1
);
$query = new WP_Query( $args );

【讨论】:

  • 没有变化:/也许我的其他一些设置会有所不同?主题:二十五 我已将特定主页设置为首页,因此我可以应用自定义页面模板 php 文件。
  • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性 cmets 挤满你的代码,因为这会降低代码和解释的可读性!
  • @dovid,你的主页是哪一个?索引.php?或者你可以检查任何静态页面吗?
  • 现在,我在想我的问题是没有指向数组的指针来增加帖子。
  • @Mickey 我已将网站的首页设置为我称为“主页”的新页面,该页面从我正在构建的名为 hompepage.php 的自定义模板运行。
【解决方案2】:

我终于弄明白了!原来,

echo '<li>' . get_template_part( 'content', 'page' ) . '</li>';

应该在 while 循环内。

这就是为什么它只给我看第一个。没有分页问题。

在那之后,唯一的问题是链接由于某种原因无法正常工作 - 所以我摆脱了 get_template_part 函数中对“页面”的调用。现在一切正常!

不管怎样,谢谢大家的帮助!

【讨论】:

    猜你喜欢
    • 2017-01-11
    • 2023-03-30
    • 1970-01-01
    • 2018-01-14
    • 2023-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多