Sticky a random post every page refresh

Question

I’m trying to sticky and display a random post on homepage.

The code works 90% of the time, displaying a random sticky post, yet other 10% of the time not a single post is marked as sticky. After page refresh it starts showing sticky posts again.

What could be the issue here?

function create_random_sticky() {

    if (!is_front_page() ) {
            $stickies = array();
            $updated = update_option( 'sticky_posts', $stickies );
            return;
    }

    $args = array( 
        'orderby' => 'rand',
        'posts_per_page' => '1', 
    );

    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) : $loop->the_post();
    $post_id = get_the_ID();
    endwhile;

    $stickies = array($post_id);
    $updated = update_option( 'sticky_posts', $stickies );


}
add_action( 'template_redirect', 'create_random_sticky' );
0
andy 7 months 0 Answers 91 views 0

Leave an answer