WordPress Snippets at WPcustoms

modify custom post type query on archive page

Set a custom order for posts in a custom post type on archive pages. This function is a nice example how to change the query settings for cpts and using conditionals


/**
 * Snippet Name: modify custom post type query on archive page
 * Snippet URL: https://wpcustoms.net/snippets/modify-custom-post-type-query-on-archive-page/
 */
  function wpc_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', 'wpc_order_post_type_archive' );