Sticky Post query in wordpress
For some reason it only displays the stick post if only belongs to the first 5 news posts,
Is that the case? is it possible to query the whole category for sticky postst?
Not the older ones.
I have below function for sticky posts,
function wpb_latest_sticky() {
/* Get all sticky posts */
$sticky = get_option( 'sticky_posts' );
/* Sort the stickies with the newest ones at the top */
rsort( $sticky );
/* Get the 5 newest stickies (change 5 for a different number) */
$sticky = array_slice( $sticky, 0, 5 );
/* Query sticky posts */
$the_query = new WP_Query( array( 'post__in' => $sticky, 'ignore_sticky_posts' => 1 ) );
// The Loop
if ( $the_query->have_posts() ) {
$return .= '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$return .= '<li><a href="' .get_permalink(). '" title="' . get_the_title() . '">' . get_the_title() . '</a><br />' . get_the_excerpt(). '</li>';
}
$return .= '</ul>';
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
return $return;
}
add_shortcode(‘latest_stickies’, ‘wpb_latest_sticky’);
add_filter(‘the_posts’, ‘bump_sticky_posts_to_top’);
function bump_sticky_posts_to_top($posts) {
$stickies = array();
foreach($posts as $i => $post) {
if(is_sticky($post->ID)) {
$stickies[] = $post;
unset($posts[$i]);
}
}
return array_merge($stickies, $posts);
}
Below code in my wordpress template
<?php
query_posts(array('category_name' => 'news' , 'posts_per_page' => 5));
if ( have_posts() ) :
while ( have_posts() ) : the_post(); ?>
<div class="archive archive-item">
<div class="archive-content">
<div class="image-wrap">
<?php
if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) {
echo get_the_post_thumbnail($post->ID,'large');
} else { ?>
<img src="<?php echo bloginfo('template_directory'); ?>/assets/images/default-news-image.jpg" alt="archive-default">
<?php } ?>
</div>
<div class="post-content">
<small class="date" id="post-meta_<?php the_ID(); ?>"><?php the_time(__('jS F Y')) ?><?php if (current_user_can( 'delete_others_posts' )) {?> <span>|</span> <?php edit_post_link('Edit'); ?><?php } ?></small>
<h2><a href="<?php the_permalink() ?>" title="<?php printf( esc_attr__('Permalink to %s'), the_title_attribute('echo=0') ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
</div>
</div>
</div>
<?php
$categories = get_the_category();
endwhile;
else:
echo '<p class="no-posts">No posts found.<p>';
endif;
Leave an answer
You must login or register to add a new answer .