0

So I would like to have an archive that displays its posts in a random order.

<?php    
    $query = new WP_Query($query_string."&orderby=rand");
?>

But also then if the user chooses they can order the posts differently by clicking a button.

<?php
    $sort_date = add_query_arg(array('orderby'=>'date','order'=>'asc'));
    $sort_name = add_query_arg(array('orderby'=>'title','order'=>'asc'));
?>

<div class="sort">
    Sort by: <a href="<?php echo $sort_date; ?>">Date Listed</a> | <a href="<?php echo  $sort_name; ?>">Name</a>
</div>

These 2 things work separately but when I try and use them together the archive just keeps display the posts randomly.

How can I get these 2 to work together?

3
  • Order parameter in your WP_Query statement is missing. Commented Sep 2, 2014 at 3:24
  • Thats because its not needed, WP_Query Order parameter defaults to desc.
    – ngearing
    Commented Sep 2, 2014 at 3:34
  • Sorry, I meant orderby. Anyway, you are always querying with orderby=rand. So, obviously it will always show random post. You should have some condition check to have value of orderby to rand or date or title. Commented Sep 2, 2014 at 4:04

2 Answers 2

1

Use pre_get_posts instead..

function my_archive_query_override( $query ) {
    if ( $query->is_archive() && $query->is_main_query() ) {
        $query->set( 'orderby', 'rand' );
    }
}
add_action( 'pre_get_posts', 'my_archive_query_override' );

For that user selectable part, you can use AJAX to accomplish that.

1

So I finally figured it out.

Using pre_get_posts and the $_GET global var to check if any query args have been added works a treat.

I used the follow code to get the desired results.

function my_pre_get_posts($query) {
    if(
        $query->is_main_query() && 
        is_archive() && 
        !isset($_GET['orderby']) && // checks for query args
        !is_admin()
    ) {
        $query->set('orderby','rand');
    }
add_action('pre_get_posts', 'my_pre_get_posts');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.