Ordering local templates alphabetically

Hi there! I’m aware there’s already a request for adding categories to the local templates (and that would be GREAT). But since I don’t know if that is going to happen (and when) I would like to find a simpler solution in the meantime, and ease the navigation through the local templates by simply ordering them alphabetically.

I don’t know if you guys could share a php snippet or any sort of code that could help me at least order the local templates alphabetically, because ordering them by newest to older is a mess :S.

Thanks in advance!

Here’s the code I use.

function set_gblocks_cpt_order($wp_query) {
if (is_admin()) {

// Get the post type from the query  
$post_type = $wp_query->query['post_type'];  

if ( $post_type == 'gblocks_global_style') {  

  // 'orderby' value can be any column name  
  $wp_query->set('orderby', 'title');  

  // 'order' value can be ASC or DESC  
  $wp_query->set('order', 'ASC');  
}
  
if ( $post_type == 'gblocks_templates') {  

  // 'orderby' value can be any column name  
  $wp_query->set('orderby', 'title');  

  // 'order' value can be ASC or DESC  
  $wp_query->set('order', 'ASC');  
}

}
}
add_filter(‘pre_get_posts’, ‘set_gblocks_cpt_order’);

1 Like

Hi @TheFrameGuy ! Thanks for responding!

I tried your code and yes, it works when I go to the local templates page, but my intention was to display the local templates alphabetically when I add a block (see screenshot) since is from where I use them most of the time. Any ideas on how to do that?

And since we’re at it and you look way savvier than me in terms of php, have you by any chance discover a way to display them in categories or something?

Thanks in advance!

@eduardsans, ahhhh, I totally understand now what you are looking for. I have no answer for what you are looking for, but I’d like that too! Oh, and I’m not PHP savvy, but I’ve found some good code snippets over the years.

@TheFrameGuy Too bad! Thanks anyway :slight_smile: Let’s see if someone can provide another code that fits better my intentions.

My guess is that more or less the same code should work, if only it was targeted to the right place.

Any answer from a member of official support would be appreciated. It’s been 7 days and I’m still struggling to find a solution to this.

@eduardsans try this code:

add_filter('pre_get_posts', 'set_gb_local_templates_order_by', 100);
function set_gb_local_templates_order_by( $wp_query ) {
	if ( 'gblocks_templates' === $wp_query->get( 'post_type' ) ) {
		$wp_query->set( 'orderby', 'title' );
		$wp_query->set( 'order', 'ASC' );
	}
	return $wp_query;
}
1 Like

Yesss!! Finally! Thanks a looooot @JeanPaiva ! have a great day :smiley:

Glad to help man! Great day for you too