Post Category Links Ordered by Parent and Child Categories in Bricks

A user asks:

How do I sort term name, it has to be parent category first then the sub-category. The red arrows indicates parent category.

As far as know, there is built-in setting or a filter in Bricks builder to output comma-separated post categories with parent categories at the beginning followed by child categories.

However, we can write a custom function that gets all the categories assigned to the current post, filter them to get parent and child categories as separate arrays, merge these arrays in that order, loop through the combined array and construct the HTML to output category names linking to the corresponding category archive pages.

Then we simply use this function as a dynamic data tag.

Add the following in child theme‘s functions.php or a code snippets plugin:

// Function to output comma-separated category links for the current post with parent categories at the beginning and child categories at the end.
function bl_post_category_links_ordered() {
		$categories = get_the_category();
		$separator = ', ';
		$output = '';
		if ( ! empty( $categories ) ) {
				$parent_categories = array_filter( $categories, function( $category ) {
						return $category->parent === 0;
				} );
				$child_categories = array_filter( $categories, function( $category ) {
						return $category->parent !== 0;
				} );
				$categories = array_merge( $parent_categories, $child_categories );
				foreach( $categories as $category ) {
						$output .= sprintf(
							'<a href="%s" title="%s">%s</a>%s',
							esc_url( get_category_link( $category->term_id ) ),
							esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ),
							esc_html( $category->name ),
							$separator
						);

				}
				return trim( $output, $separator );
		}
}

Inside a Bricks query loop, in a Basic Text element or Post element’s field, paste

{echo:bl_post_category_links_ordered}

to display the post category links that are ordered by parent categories first and then child categories.

Instant access to all 250+ Bricks code tutorials with BricksLabs Pro

Leave the first comment