Posted on Leave a comment

Get sticky post – WordPress

Sticky Post is a method used to capture any post, put it in a convenient place for visitors to see every time they visit the site.

Sticky Post has been used since the old WordPress version until now. It is useful and easy to capture the attention of website visitors.

For web developers using WordPress and PHP forms, here is an easy example to implement Sticky Post. Please follow or copy the code below.

<?php
$sticky = get_option('sticky_posts');
if (!empty($sticky)){
    echo '<section class="py-5 text-center container">';
    echo '<div class="row py-lg-5">';
    rsort($sticky);
    $args = array(
        'posts_per_page' => 1,
        'post_status'  => 'publish',
        'post__in' => $sticky,
        'orderby' => 'rand',
        'order'  => 'desc'
    );
    $sticky_post =  new WP_Query($args);
    if ($sticky_post->have_posts()) {
         $sticky_post->the_post();
        ?>
        <div class="col-lg-6 col-md-8 mx-auto">
            <h1 class="fw-light display-6 lh-base"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
            <p class="lead text-muted">
                <?php echo the_excerpt();?>
            </p>
            <p>
              <a href="<?php the_permalink(); ?>" class="btn btn-primary my-2"><i class="fas fa-book-open-reader"></i></a>
              <a href="#more" class="btn btn-secondary my-2"><i class="fas fa-list-alt"></i></a>
            </p>
        </div>
        <?php
    }
    echo '</div>';
    echo '</section>';
}
?>

What you need to see just a few lines below:

$sticky = get_option('sticky_posts');
if (!empty($sticky)){
    echo '<section class="py-5 text-center container">';
    echo '<div class="row py-lg-5">';
    rsort($sticky);
    $args = array(
        'posts_per_page' => 1,
        'post_status'  => 'publish',
        'post__in' => $sticky,
        'orderby' => 'rand',
        'order'  => 'desc'
    );
}

And one more step is to modify your post as Sticky content in your wordpress post dashboard. It is just very simple by only tick on the “Make the post sticky”.

Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *