WordPress query to show only sticky posts

Following is my wordpress query in which i want to show only sticky posts but the query is not showing any posts. Also I set two posts as sticky so that part is checked!!!. Kindly let me know how to modify this query so it will only show the posts which are sticky

<?php 
   $wp_query = null; 
  $wp_query =  new WP_Query(array(
 'posts_per_page' => 2,
 //'paged' => get_query_var('paged'),
 'post_type' => 'post',
'post__in'  =>  'sticky_posts',
 //'post__not_in' => array($lastpost),
 'post_status' => 'publish',
 'caller_get_posts'=> 0 ));

  while ($wp_query->have_posts()) : $wp_query->the_post(); $lastpost[] = get_the_ID();
?>

Related posts

Leave a Reply

2 comments

  1. Query which will show only sticky posts:

    // get sticky posts from DB
    $sticky = get_option('sticky_posts');
    // check if there are any
    if (!empty($sticky)) {
        // optional: sort the newest IDs first
        rsort($sticky);
        // override the query
        $args = array(
            'post__in' => $sticky
        );
        query_posts($args);
        // the loop
        while (have_posts()) {
             the_post();
             // your code
        }
    }
    
  2. The query_posts() function creates a new WP_Query() not before the current query is set up, meaning this is not the best efficient method and will perform extra SQL requests.

    Use the ‘pre_get_posts’ hook to be safe, like

    function sticky_home( $query ) {
    
        $sticky = get_option('sticky_posts');
    
        if (! empty($sticky)) {
            if ( $query->is_home() && $query->is_main_query() ) {
                 $query->set( 'post__in', $sticky );
            }
        }
    
    } add_action( 'pre_get_posts', 'sticky_home' );