I’m trying to sort posts by title (instead of date) within a custom post type archive in Elementor. I’ve set up a custom query and trying to target the custom post type ‘glossary’ but I’m doing something wrong… can anyone help?
add_action( 'pre_get_posts', 'glossary_sort_order');
function glossary_sort_order($query){
if(is_post_type_archive( $post_type, 'glossary', true )):
$query->set( 'order', 'ASC' );
$query->set( 'orderby', 'title' );
endif;
};
Thank you
2
Answers
The previous answer still didn't work for me, although I do appreciate the helpful feedback from @amarinediary
Here is the code that eventually worked for me:
});
Thank you
You were close!
pre_get_posts
is the right action hook, but you’ve got to check if it’s the main query too.We also want to exclude the admin side (really important) with
! is_admin()
, finally we check if we are on anarchive.php
page and we check the post type usingget_query_var()
.is_admin()
is_archive()
is_main_query(
)get_query_var()
Learn more
WP_Query
@ https://developer.wordpress.org/reference/classes/wp_query/