Question

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!

Was it helpful?

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)

OTHER TIPS

Am I understanding you correct you want to have two loops, one where you fetch the 3 most recent posts, and one where you fetch the 7 most recent posts? If so you can do a WP_Query and pass in arguments on how to order the query with 'order' and 'orderby'.

$args = array(
    'posts_per_page' => 3, // get three posts
    'order' => 'DESC', // Order ascending or decending, use desc for latest.
    'orderby' => 'date' // Tell our query to sort by date.
);

$query = new WP_Query($args);

if($query->have_posts()) : while($query->have_posts()) : $query->the_post();
    // Do what you want with your 3 latest posts.
endwhile; endif;

See the documentation on WP_Query for references. http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

If I misunderstood your question, let me know!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top