Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

diego-betto commented Apr 3, 2017

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