Pergunta

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

Foi útil?

Solução

If the given code is correct it might be the missing brackets on your pre_get_posts conditional. Let's format it with proper indentation and spacing:

function alter_query( $query ) {
    
    if( $query->is_main_query() &&  is_home() )
        $query->set( 'cat', '2' );
        
    $query->set( 'orderby', 'rand' );
    
}
add_action( 'pre_get_posts','alter_query' );

Because there's no brackets for your conditional statement, it will run the first line inside the conditional and all other lines outside. It's shorthand. To fix this we just need to add brackets:

function alter_query( $query ) {
    
    if( $query->is_main_query() && is_home() ) {
    
        $query->set( 'cat', '2' );
        $query->set( 'orderby', 'rand' );
        
    }
    
}
add_action( 'pre_get_posts','alter_query' );

By encapsulating the additional functionality in brackets we ensure that all statements are run only if that condition is met.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a wordpress.stackexchange
scroll top