Sticky posts, then normal posts, but limited amount (in wp query)

☆樱花仙子☆ 提交于 2019-12-11 07:16:26

问题


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:


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 );


来源:https://stackoverflow.com/questions/22437865/sticky-posts-then-normal-posts-but-limited-amount-in-wp-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!