Sticky posts, then normal posts, but limited amoun

2019-08-11 19:42发布

So on the first page of the project of which I'm working on I need to display a total of three posts from my custom post type 'project'.

This post type also have some sticky posts which I wish to display first. And then the regular ones after. But it is important that the number of posts are three regardless of sticky amount.

I've found a bunch of examples, but I can't get it right. Is there for example a way to query sticky posts first and limit those to three, and have a second query that limits the post number to three minus amount of sticky posts?

1条回答
趁早两清
2楼-- · 2019-08-11 20:10

Easy way is to do in two queries, try (presence of 'ignore_sticky_posts' on both args. is not a mistake, it is just about the order), was tested:

$sticky = get_option( 'sticky_posts' );
$args = array(
 'ignore_sticky_posts' => 1,
  'post__in' => $sticky,
  'posts_per_page' => 3,
);

$the_query = new WP_Query( $args );
$total_posts_onpage = 5;
$nuber_of_noSticky = $total_posts_onpage - $the_query->found_posts;

// code to display sticky ones
wp_reset_postdata();

//second query
$args = array(
 'ignore_sticky_posts' => 1,
 'post__not_in' => $sticky,
 'posts_per_page' => $nuber_of_noSticky,
);

$the_query = new WP_Query( $args );
查看更多
登录 后发表回答