How to change posts order on Category and Tag archives?
-
22-04-2021 - |
Frage
WordPress by default order posts in descending order by date. But I want them to be in ascending order by date.
How do I turn the order to ascending only for tags and category? I don't want blog post orders to change.
Lösung
You can use pre_get_posts
action to modify this order. Here's the code:
function my_change_posts_order( $query ){
if ( ! is_admin() && ( is_category() || is_tag() ) && $query->is_main_query() ) {
$query->set( 'order', 'ASC' );
}
};
add_action( 'pre_get_posts', 'my_change_posts_order');
What we do here is:
- We're adding our function that will modify params for WP_Queries
- We make sure that it will change only main query (the one created by WordPress) and only on category and tag listings (
is_category()
andis_tag()
). - We change the order of posts for these pages by setting
order
toASC
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit wordpress.stackexchange