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:

$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>
<?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;

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.

tomtomthompson 2 months 0 Answers 8 views 0

Leave an answer