获取博客页面上的最新帖子

因此,我正在寻找一种获取最新帖子的方法,以便以与其他帖子不同的方式显示它。在设置中,我有我的“博客”页面来显示帖子,通常每个人都会这样做。


我尝试的第一件事(另一个问题的答案)是使用正常循环,我的意思是,if (have_posts())...while(have_posts())..etc。在该IF之上,放置另一个IF以获取最新帖子,通过这种方式我可以为我的最后一个帖子设置样式。但由于我有分页,在每个页面上,最新的帖子实际上是该页面的最新帖子,而不是真正的最新帖子。希望这是可以理解的。


我的第二次尝试是从正常循环中排除最新帖子,为此我使用了一篇文章中的片段,该文章解释了如何排除最新帖子并使用pre_get_posts和found_posts保持分页工作,因此我的代码如下:


add_action('pre_get_posts', 'myprefix_query_offset', 1 );

function myprefix_query_offset(&$query) {


    //Before anything else, make sure this is the right query...

    if ( ! $query->is_home() ) {

        return;

    }


    //First, define your desired offset...

    $offset = 1;


    //Next, determine how many posts per page you want (we'll use WordPress's settings)

    $ppp = get_option('posts_per_page');


    //Next, detect and handle pagination...

    if ( $query->is_paged ) {


        //Manually determine page query offset (offset + current page (minus one) x posts per page)

        $page_offset = $offset + ( ($query->query_vars['paged']-1) * $ppp );


        //Apply adjust page offset

        $query->set('offset', $page_offset );


    }

    else {


        //This is the first page. Just use the offset...

        $query->set('offset',$offset);


    }

}


add_filter('found_posts', 'myprefix_adjust_offset_pagination', 1, 2 );

function myprefix_adjust_offset_pagination($found_posts, $query) {


    //Define our offset again...

    $offset = 1;


    //Ensure we're modifying the right query object...

    if ( $query->is_home() ) {

        //Reduce WordPress's found_posts count by the offset...

        return $found_posts - $offset;

    }

    return $found_posts;

}

到目前为止一切顺利,这段代码正在运行,它不包括最新的帖子并且分页正在运行,但现在我的问题是,我如何获得最新的帖子?我尝试在home.php 中的循环上方使用wp_query来获取该单个最新帖子,但意识到pre_get_posts覆盖了wp_query?


我怎样才能解决这个问题并获得最新的帖子?我必须做相反的事情吗?我的意思是,首先获取最新帖子,然后为其余帖子创建自定义循环,但如何管理分页?


繁华开满天机
浏览 132回答 1
1回答

开心每一天1111

您的分页系统工作正常。您可以做什么,它使用wp_get_recent_posts检索最新帖子:$latestPosts = wp_get_recent_posts(['numberposts' => 1]);$latestPost = $latestPosts ? current($latestPosts) : null;然后在你的 div 中,你可以用$latestPost.<?php if ($latestPost): ?>&nbsp; &nbsp; <div class="blog-item featured-item">&nbsp; &nbsp; &nbsp; &nbsp; // display latest post here&nbsp; &nbsp; </div><?php endif; ?>要使上述工作正常运行,您需要pre_get_posts稍微更改一下以确保仅更改主查询时的查询:if (! $query->is_home() || ! $query->is_main_query()) {&nbsp; &nbsp; return;}
打开App,查看更多内容
随时随地看视频慕课网APP