Search code examples
phpwordpressposts

WP_Query: Show posts in a certain order for a certain time


I would like to display each post in the order specified under post__in on my home page for one day. That means first the post with ID 3 should be shown until 23:59:59, then the post with ID 1 for 24 hours until 23:59:59, then the post with ID 2 and so on. When all posts have been shown, it should start again from the beginning. Does anyone have an idea how to implement this?

function post_of_the_day( $query_args) {
    global $post;
    
    $query_args = array(
            'post_type'      => 'example_post_type',
            'posts_per_page' => 1,
            'post__in'       => array(3, 1, 2, 4, 7, 6, 5)
        );

     return $query_args;

     }

Solution

  • If you want just one post per day of the week, you can make use of PHP's date() function, with the 'w' format string. It returns 0 for Sunday, 1 for Monday, 6 for Saturday, etc. Then you can use that as an index to find the one post ID you want from your array, and use the 'p' argument in your WP_Query() arguments

    function post_of_the_day( $query_args ){
        $post_ids = array( 3, 1, 2, 4, 7, 6, 5 ); // List of available ID's
        $id_index = absint( date('w') );          // 0-6 based on day of the week
    
        $query_args = array(
            'p' => $post_ids[$id_index],          // 3 on Sun, 1 on Mon, 5 on Sat
            'post_type' => 'example_post_type'    // Your post type
        );
        
        return $query_args;
    }
    

    You shouldn't need to query all 7 posts with post__in if you just need the one. Generally, you want to try and retrieve as little information as necessary for speed, optimization, and ease-of-maintenance.