0

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;

     }
RaWa
  • 25
  • 5

1 Answers1

1

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.

Xhynk
  • 13,513
  • 8
  • 32
  • 69
  • Thank you very much! This helped me a lot! Can this also be applied to the weeks of a month or to the weeks of a year? So that not a post per day, but per week is shown? @Xhynk – RaWa Dec 22 '20 at 20:33
  • 1
    Of course, anything you can get a number for. `date('n')` gets you the 1-12 number of the month, `date('W')` gets you the 1-52 number of the week (starts on mondays), and a bit more involved, but here's an answer for how to get ["current week of the month as a number"](https://stackoverflow.com/questions/32615861/get-week-number-in-month-from-date-in-php/32624747) – Xhynk Dec 22 '20 at 21:38
  • Perfect! Thanks a lot! – RaWa Dec 22 '20 at 22:14