Sort results by name & asc order on Archive.php

I currently use the following code to list posts in Archive.php but I want the results to be ordered by name in ascending order, I have checked the codex but the answer isn’t clear to me, how can I get this working?

<?php $post = $posts[0]; // ?>

Thanks in advance.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The easiest way to do this is to use a hook (the pre_get_posts hook) to change the order. But you should check that the query is one for which you do want to alter the order! (is_archive() or is_post_type_archive() should be sufficient.)

For instance, put the following in your theme’s functions.php…

add_action( 'pre_get_posts', 'my_change_sort_order'); 
    function my_change_sort_order($query){
        if(is_archive()):
         //If you wanted it for the archive of a custom post type use: is_post_type_archive( $post_type )
           //Set the order ASC or DESC
           $query->set( 'order', 'ASC' );
           //Set the orderby
           $query->set( 'orderby', 'title' );
        endif;    
    };

Method 2

<?php
// we add this, to show all posts in our
// Glossary sorted alphabetically
if ( is_category('Glossary') )  {
    $args = array( 
        'posts_per_page' => -1, 
        'orderby'        => 'title', 
        'order'          => 'ASC' 
    );
    $glossaryposts = get_posts( $args );
}
foreach( $glossaryposts as $post ) : setup_postdata( $post );
    ?>
    <li><a href="<?php the_permalink(); ?>" rel="nofollow noreferrer noopener"><?php the_title(); ?></a></li>
<?php endforeach; ?>

Method 3

further to Stephen’s answer, if you want to just query and order by the title, you could use this in your template file:

$args = ( array(
'order' => 'ASC',
'orderby' => 'title',
 ) );

query_posts($args);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x