Ordering posts by publish date not working?
My site has a "Portfolio" page, which pulls in posts in category 3. Here is my code which selects the posts:
<?php
$args = array('cat' => 3,
'post_type' => 'post',
'orderby' => 'date',
'order' => 'DESC');
$postslist = get_posts( $args );
foreach ($postslist as $post) : setup_postdata($post);
?>
<div class="portfolio-item">
<?php the_post_thumbnail() ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>
<?php endforeach; ?>
But the posts appear in a random order each time the page is refreshed, even though I have ‘orderby’ and ‘order’ in the arguments. There seems to be a strange interaction with a short section of code in functions.php which looks like this;
<?php
add_action('pre_get_posts','alter_query');
function alter_query($query){
if ($query->is_main_query() && is_home())
$query->set('cat', '2');
$query->set('orderby', 'rand');
}
?>
This code shows a random post from all posts of category 2 on the homepage.
Whilst this line is included;
$query->set('cat', '2');
The orderby => date and order => DESC stop working on the portfolio page, but I need that line to select only category 2 posts for the homepage.
If anyone could point me in the direction of why this might be happening I’d be very grateful.
Thanks
Leave an answer
You must login or register to add a new answer .