Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress query to show only sticky posts

Tags:

php

wordpress

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();
?>
like image 228
user2304394 Avatar asked Nov 06 '13 14:11

user2304394


2 Answers

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
    }
}
like image 155
sebapalus Avatar answered Sep 21 '22 23:09

sebapalus


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' );
like image 45
Svetlana Silina Avatar answered Sep 20 '22 23:09

Svetlana Silina