Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show latest 2 sticky posts at WordPress home page

Tags:

php

wordpress

I am cutomizing my WordPress theme and I want to add latest 2 sticky post at the top of my Wordpress home page. For that I use following code:

<div class="trending-right">
   <?php
     $sticky = get_option( 'sticky_posts' ); // Get all sticky posts
     rsort( $sticky ); // Sort the stickies, latest first
     $sticky = array_slice( $sticky, 0, 2 ); // Number of stickies to show
     query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1 ) ); // The query

     if (have_posts() ) { while ( have_posts() ) : the_post(); ?>
     <div class="trend-post">
     <div class="thumb"><?php the_post_thumbnail(array(150,100)); ?></div>
     <div class="title"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></div>
     </div>
     <?php endwhile;?>
     <?php } else { echo ""; }?>

</div>

Now the code works OK and shows the latest 2 sticky posts however it also removes all other listed posts from home page and shows only those 2 sticky posts. I tried replacing query_posts with new WP_Query but in that case it shows ALL sticky posts instead of only 2.

Any suggestion how to tweak above code and make it work?

like image 847
Boris Zegarac Avatar asked Dec 21 '25 00:12

Boris Zegarac


1 Answers

Looking at your code, I am assuming you've just shown us the sticky loop and there is another query to display the other posts elsewhere in the template?. You should use wp_reset_query(); after your custom query, here's the entry in the Codex;

Wordpress - resetting custom query

like image 186
McNab Avatar answered Dec 23 '25 16:12

McNab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!