php - Wordpress 只在 front-page.php 上显示最近的帖子

标签 php html css wordpress

我无法弄清楚如何确保只有我最近的帖子显示在我的 front-page.php 文件的首页上,因为我有一些自定义帖子类型并且希望我最近的帖子仅显示在我最近的自定义帖子类型下方。

抱歉,如果这没有意义,基本上我只是想知道将什么添加到 wordpress 循环中以确保它只给我最新的帖子,而不是其他帖子。

        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <div class="section_title">
            <h2>Recent Update:</h2>
        </div>
        <h1><?php the_title(); ?></h1>
        <p><?php the_content(); ?></p>
        <p><a href="<?php the_permalink(); ?>" class="btn right">Read More</a></p>
    </div>
    <div class="front_page_image">
        <img src="images/annoyed_victoria.jpg">
    </div>
</div>

<?php endwhile; else: ?>

<?php endif; ?>

最佳答案

您可以使用 pre_get_posts钩子(Hook)将 posts_per_page 限制为 1。

将以下内容添加到您的 functions.php。

function my_main_query($query){
    if( !is_admin() && $query->is_main_query() ){
        $query->set( 'posts_per_page', 1 );
    }
}
add_action('pre_get_posts','my_main_query');

感谢 Nathan Dawson 指出 query_posts() 的缺陷。

参见 Wordpress Codex有关循环以及如何更改循环的更多信息。

关于php - Wordpress 只在 front-page.php 上显示最近的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21566856/

相关文章:

javascript - 使用 AJAX 更新从数据库(mysql)检索的数据

php - 通过不使用不同查询的 PHP MYSQL 循环创建 JSON

php - 双重MySQL查询

php - 使用ajax从mysql数据库中列出记录

javascript - 使用 Javascript 创建自定义控件

html - 绑定(bind)到主机的 css 属性(而不是类)

php - bootstrap.min.css 加载资源失败:net::ERR_CONNECTION_REFUSED

javascript - JQuery UI 对话框关闭屏幕

javascript - 使用 Javascript/CSS 生成方框网格

javascript - HTML 标签下的这个奇怪的空白是什么?