First, the order option only allows ‘ASC’ or ‘DESC’ and at this point you are telling the request to return the results ordered by date – this means they will always come back in the same order.
Secondly, the orderby displays the results of teh query in the order that you have chosen. That is important because if you only return one row, it does’t matte what the orderby is.
I would suggest leaving the ‘posts_per_page’ at -1, get rid of the ‘order’, set ‘orderby’ to rand and then change the while loop to do a ‘break;’ after the $loop->the_post();
Don’t forget to put the whole while inside brackets since you will have mofe than one PHP statement.
Hi Juggledad,
Thanks very much for getting back to me. I am not 100% sure what you mean by the break after $loop->the_post.
Could you give me an example? Here is the full query so you can help me a little more.
<?php
$args = array(
'post_type' => 'milo-books',
'posts_per_page' => -1,
'orderby' => 'rand'
);
$loop = new WP_Query( $args );
if ($loop->have_posts()): while ($loop->have_posts()) : $loop->the_post();
<h2>Featured Title</h2>
<div class="featured-content-container">
// Main Content Here
</div>
<?php endwhile; ?>
<?php else: ?>
<h2>No Book Info Found.</h2>
<?php endif; ?>
<?php wp_reset_postdata();?>
try this
<?php
$args = array(
'post_type' => 'milo-books',
'posts_per_page' => -1,
'orderby' => 'rand'
);
$loop = new WP_Query( $args );
if ($loop->have_posts()): while ($loop->have_posts()) {
$loop->the_post();
break;
}
<h2>Featured Title</h2>
<div class="featured-content-container">
// Main Content Here
</div>
<?php endwhile; ?>
<?php else: ?>
<h2>No Book Info Found.</h2>
<?php endif; ?>
<?php wp_reset_postdata();?>
Hi Juggledad,
Thanks for sending through the code. I am getting an error which says “Unexpected T_ENDWHILE”
Any ideas?
Dan
For some reason once I deleted the code you supplied and added back in the original code. It started working.
Maybe it was the random setting I had wrong.
Many thanks for the help. I appreciate it.
I make sure to check it a few times and see if you are getting a random post and not just the same one over and over.