How to order wordpress posts and custom post_types

When working on a recent project i needed to display a custom post_type in a specific order, to do this we need to hook into the main wordpress for the post or custom post_types archive and override the default arguments with our custom order and any other parameters we wish to change.

Hook into WordPress post and custom post_type querys

We can hook into all wordpress queries which run using the action ‘pre_get_posts’, now we need to target the main archive query and set our query arguments. When hooking into the core WP_Query we can either replace the query completely or amend it with the custom arguments, for this example we will add the custom arguments to the existing $query using the $query->set() method.

 * Order post_type by the custom field "featured"
function jc_order_post_type_archive( $query ) {
if($query->is_main_query() && is_post_type_archive('post_type' )){
		// order post_type and remove pagination
		$query->set('posts_per_page', -1);
		$query->set('orderby', 'meta_value');
		$query->set('meta_key', 'featured');
		$query->set('order', 'DESC');
add_action( 'pre_get_posts', 'jc_order_post_type_archive' );

Liked this article? help spread the word.