【发布时间】:2019-06-28 14:58:56
【问题描述】:
因此,我正在寻找一种获取最新帖子的方法,以便以与其他帖子不同的方式显示它。在设置中,我有我的“博客”页面来显示帖子,就像每个人一样。
我尝试的第一件事(另一个问题的答案)是使用正常循环,我的意思是,if (have_posts())...while(have_posts())..etc强>。在那个 IF 之上,放置另一个 IF 只是为了获取最新的帖子,通过这种方式我可以为我的最后一个帖子设置样式。但是由于我有分页,在每一页上,最新的帖子实际上是该页面的最新帖子,而不是真正的最新帖子。希望这是可以理解的。
我的第二次尝试是从正常循环中排除最新帖子,为此我使用了一篇文章中的 sn-p,该文章解释了如何排除最新帖子并使用 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?
我怎样才能解决这个问题并获得最新的帖子?我必须做相反的事情吗?我的意思是,首先获取最新的帖子,然后为其余帖子创建自定义循环,但是如何管理分页?
这是我目前在 home.php 中的 html
<div class="blog-list">
<div class="blog-item featured-item">
// display latest post here
</div>
<?php if ( have_posts() ): ?>
<div class="teaser-inner mb-4">
<div class="row">
<?php while ( have_posts() ): ?>
<?php the_post(); ?>
<div class="blog-item col-md-6 mb-3 mb-sm-5">
<div class="row">
<div class="col-6 col-md-4">
<?php $img_url = get_the_post_thumbnail_url(get_the_ID(),'full'); ?>
<a href="<?php echo esc_url( get_permalink() ); ?>" class="blog-link">
<div class="blog-item-img bg-cover" style="background-image:url(<?php echo esc_url($img_url); ?>)"></div>
</a>
</div>
<div class="col-6 col-md-8">
<a href="<?php echo esc_url( get_permalink() ); ?>"><?php the_title(); ?></a>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
<div class="blog-pagination">
<?php echo paginate_links(); ?>
</div>
<?php endif; ?>
</div>
感谢任何线索。
【问题讨论】:
-
为什么要从循环中排除页面的最新帖子进行分页?为什么不只显示查询中的第一个帖子并遍历其余帖子?
-
@ChinLeung 我想我在我的问题中提到了这一点。我实际上是这样做的,但是例如,如果您有分页并且您在第 2 页,那么第一个帖子是当前页面(第 2 页)的最新帖子,而不是真正的最新帖子。
-
哦!对不起,我误会了。我以为你想显示当前页面的最新帖子。
标签: php wordpress wordpress-theming