Search code examples
phphtmlwordpressblogs

How can I query recent 5 sticky posts on WordPress


I've tried using this code on loop, and it gives me just one post from the sticky posts:

<div id="content">
<ul class="disclosure table group">
<?php
$sticky = get_option( 'sticky_posts' );
$args = array(
    'posts_per_page' => 10,
    'post__in'  => $sticky,
    'ignore_sticky_posts' => 1
);

$query = new WP_Query( $args );
if ( isset($sticky[0]) ) {
?>

    <li style="text-align: justify; font-weight: 500; color: #b30404;">
<a href="<?php the_permalink(); ?>" style="color: #b30404;" title="<?php the_title(); ?>"><span style="font-size: 15px;"><?php the_title(); ?> </span></a>
</li>
<?php } ?></ul></div>

and I want it showing 5. I have tried adding this line to the code but not working:

$sticky = array_slice( $sticky, 0, 5 );

I need help on how I can make this code show 5 latest posts (only sticky posts). Or give me a code I can use that's will be a solution to my request. Thanks in advance


Solution

  • $sticky = get_option( 'sticky_posts' );
    
    rsort( $sticky );
    
    $sticky = array_slice( $sticky, 0, 5 );
    
    $the_query = new WP_Query( array( 'post__in' => $sticky, 'ignore_sticky_posts' => 1 ) );
    

    try this

    and remove this line if ( isset($sticky[0]) ) {

    add this loop after the query

    if ( $the_query->have_posts() ) {
    
        while ( $the_query->have_posts() ) {
    
            $the_query->the_post();
    
            the_title();
       }
    }