WordPress.org

Ready to get started?Download WordPress

Forums

Randomizing Order of First Four Posts in a Slideshow (3 posts)

  1. rdmccoy
    Member
    Posted 1 year ago #

    Hello! I'm having trouble adapting my slideshow to my needs. Here's what I want it to do:

    1.) Display the four most recent posts from any category.
    2.) Randomize the display order of those four posts in the slideshow.
    3.) This should result in the same four most recent posts being randomly ordered whenever you refresh the page.

    Anyway, here is the code I'm working with:

    <?php $wp_query = new WP_Query(array('cat'=>of_get_option('category_slider'),'posts_per_page'=>of_get_option('postnumber_slider'))); ?>

    I've successfully randomized the slideshow by appending 'orderby' => 'rand' as the last value in the array; however, these causes the slideshow to randomize the order of every single post, rather than just the most recent four posts. ('posts_per_page' calls the theme option of four.)

    I've read in the Codex how I can limit the 'cat' value by day and month but that isn't what I need. I just need to limit the 'cat' value to the most recent four posts. Any ideas?

    Thanks!

    David
    hipstersofthecoast.com

  2. Shaun Scovil
    Member
    Posted 1 year ago #

    This should do it:

    <?php
        $args = array(
            'cat'            => of_get_option( 'category_slider' ),
            'posts_per_page' => of_get_option( 'postnumber_slider' )
        );
        $wp_query = new WP_Query( $args );
        shuffle( $wp_query->posts );
    ?>

    This solution uses the PHP shuffle() function.

  3. rdmccoy
    Member
    Posted 1 year ago #

    That's awesome. Thanks so much!

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.