Search code examples
wordpressposts

Wordpress - Post_In - Possibility to use most recent as reference


I want to load my most recent post, my 3rd most recent post and my 7th most recent post on my main page during the post fetching loop:

<?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>

post_in partly gets you there but the post id is not related to how recent your post is so i doubt it if it will do the trick with better understanding.

$query = new WP_Query( array('post__in' => array( 2, 5, 12, 14, 20 ) ) );

Is there a way to load the most recent post, the 3rd most recent and the 7th most recent?

Thanks a lot in advance!


Solution

  • Here is the base model. Increment a variable every loop ($i) then only execute code with the if statement when that variable is the first, fourth or seventh loop through.

    $i = 0;
    $query = new WP_Query($args);
    foreach ($query as $loop) {
        $i++;
        if ($i == 1 || $i == 4 || $i == 7) {
            # code...
        }
    }
    

    You could do it with the native 'in_array' function if a user was to actually set them. Maybe in a meta box, theme options or something shnazzy.

    $array = array($featured_post, $worst_post, $amazing_post)
    
    $i = 0;
    $query = new WP_Query($args);
    foreach ($query as $loop) {
        $i++;
        if ( in_array($i, $array) ) {echo 'counts equals your numbers';}
    }
    

    Also note that WP gives you a host of array arguments to query by.

    'offset' => 5 //begins your new loop at the 5th post in this case. 
    'orderby' => 'post_date' // default (I believe)
    'order' => 'DESC' // default (I believe)