Include Sticky Posts with Custom Query

I’m working with Custom Query in WordPress, Basically, I’m showing 4 most recent posts of a category having ID 4
and my query is as follows:-

$args = array(
  'post_type' => 'post' ,
  'orderby' => 'date' ,
  'order' => 'DESC' ,
  'posts_per_page' => 4,
  'cat'         => '3',
  'paged' => get_query_var('paged'),
  
); 
$q = new WP_Query($args);

This is working fine, but here I have an additional requirement. I want to add sticky posts as well i.e Posts will be stick to the top no matters these posts are recent or old, and total posts_per_page should be always 4 including sticky and recent posts.

e.g If there is no sticky post then I’ll show 4 most recent posts and no sticky post. But if there is 1 sticky post then there will be 1 sticky post and 3 most recent posts, a total of 4 posts.

What modification should I made in my Query? Thank you.

1 Answer
1

$sticky = get_option( 'sticky_posts' );

$args = array(
  'post_type'           => 'post' ,
  'orderby'             => 'date' ,
  'order'               => 'DESC' ,
  'posts_per_page'      => 4,
  'cat'                 => '3',
  'paged'               => get_query_var('paged'),
  'post__in'            => isset( $sticky[0] ) ? $sticky[0] : array(),
  'ignore_sticky_posts' => 1,
  
); 
$q = new WP_Query($args);

The above code will include only the first sticky post and if it does not exist, it will get normal posts.

If you want to show all of the existing sticky posts, then use the following code:

$args = array(
  'post_type'           => 'post' ,
  'orderby'             => 'date' ,
  'order'               => 'DESC' ,
  'posts_per_page'      => 4,
  'cat'                 => '3',
  'paged'               => get_query_var('paged'),
  'ignore_sticky_posts' => false,
  
); 
$q = new WP_Query($args);

Leave a Comment