-
johnottomagee
Hello GP Support !
I have Generate Blocks Pro.
For my posts I have three categories:
Country, Topic, Subtopic.For example: Germany (country), Communication (topic), Small Talk (subtopic).
Those three categories are presented at the
bottom of a post alphabetically:
Communication, Germany, Small Talk.Is it possible to have categories presented
based on hierarchy: Germany, Communication, Small Talk?Thanks.
John
.
-
Alvind
Hi John,
This is possible if the categories have an actual parent/child hierarchy:
Germany – no parent
Communication – parent: Germany
Small Talk – parent: CommunicationThen add this PHP snippet:
add_filter( 'get_the_terms', function( $terms, $post_id, $taxonomy ) { if ( is_admin() || 'category' !== $taxonomy || ! is_singular( 'post' ) || ! is_array( $terms ) ) { return $terms; } usort( $terms, function( $a, $b ) { $a_depth = count( get_ancestors( $a->term_id, 'category', 'taxonomy' ) ); $b_depth = count( get_ancestors( $b->term_id, 'category', 'taxonomy' ) ); // Alphabetical order when terms have the same depth. if ( $a_depth === $b_depth ) { return strcasecmp( $a->name, $b->name ); } return $a_depth <=> $b_depth; } ); return $terms; }, 10, 3 );Adding PHP: https://docs.generatepress.com/article/adding-php/
This changes the output to:
Germany, Communication, Small TalkAll three categories must remain assigned to the post if you want all three displayed. If they are three unrelated categories rather than a real parent/child chain, WordPress has no hierarchy it can use for sorting. In that case, separate taxonomies for Country, Topic, and Subtopic would be the more reliable structure.
-
johnottomagee
That was fast.
Thanks, Alvind.I did not work.
Or more likely I got something wrong.See:
https://understand-culture.com/ucstage/?cat=3375I have the Plugin Code Snippets Version 3.9.6.
Could the problem be that I am working
on a staging site?John
.
-
Hi John,
I can not see the link without logging into your site.
Can you provide an admin login? -
johnottomagee
Hello Ying,
It’s been ages.
I hope you’re doing well.I just created an admin:
[removed by admin]
-
Haha I’m great, thanks for asking 🙂
The code is working, but it is intended to only work on a single post, not the archives.
Do you want to change the order for archives and blog as well?
If so, the code can be updated to this:
add_filter( 'get_the_terms', function( $terms, $post_id, $taxonomy ) { if ( is_admin() || 'category' !== $taxonomy || ! is_array( $terms ) ) { return $terms; } usort( $terms, function( $a, $b ) { $a_depth = count( get_ancestors( $a->term_id, 'category', 'taxonomy' ) ); $b_depth = count( get_ancestors( $b->term_id, 'category', 'taxonomy' ) ); if ( $a_depth === $b_depth ) { return strcasecmp( $a->name, $b->name ); } return $a_depth <=> $b_depth; } ); return $terms; }, 10, 3 ); -
johnottomagee
That worked.
Perfect, Ying.Thank you !
-
You are welcome 🙂
-
johnottomagee
- You must be logged in to reply to this topic.