Skip to content

Instantly share code, notes, and snippets.

@clifgriffin
Created September 14, 2014 21:03
Show Gist options
  • Save clifgriffin/405fdacb94412f9cfba3 to your computer and use it in GitHub Desktop.
Save clifgriffin/405fdacb94412f9cfba3 to your computer and use it in GitHub Desktop.
Order custom post type archive by title.
<?php
// Don't incldue opening PHP tag
add_filter( 'posts_orderby' , 'custom_cpt_order' );
function custom_cpt_order( $orderby ) {
global $wpdb;
// Check if the query is for an archive
if ( is_archive() && get_query_var("post_type") == "my_custom_post_type" ) {
// Query was for archive, then set order
return "$wpdb->posts.post_title ASC";
}
return $orderby;
}
@diego-betto
Copy link

This not always works. If you filter using tax_query a limited group of items (example 3 red cards out of 21 colored cards, taxonomy "color") you'll get 9 cards (number correct), but not all red since are ordered by post_title.
example, items:

  • card "A" blue
  • card "B" red
  • card "C" green
  • card "D" red
$cards = get_posts(
	[
		'numberposts'    => -1,
		'post_type'      => 'cards',
		'tax_query'      => [
			[
				'taxonomy' => 'color',
				'field'    => 'slug',
				'terms'    => ['red'],
				'operator'  => 'IN'
			]
		],
	]
);

expected result:
"B", "D"

result
"A", "B"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment