50% discount on BricksLabs Pro Membership Lifetime Access. Use coupon: GOBRICKS

[Function] Get Term Slug in Bricks

If you are querying terms of a taxonomy (like category, post_tag or a custom one) using the awesome Query Loop feature of Bricks, there might be situations where you would like to set the hyperlink of each loop element to #<term slug>.

Ex.:

<a href="#flowers" class="brxe-a9056d brxe-container brx-nestable"><h3 class="brxe-fvnjcr brxe-heading">Flowers</h3></a>
<a href="#animals" class="brxe-a9056d brxe-container brx-nestable"><h3 class="brxe-fvnjcr brxe-heading">Animals</h3></a>
<a href="#winding-rivers" class="brxe-a9056d brxe-container brx-nestable"><h3 class="brxe-fvnjcr brxe-heading">Winding Rivers</h3></a>

As Jenn pointed in his excellent Show Product Categories Count Using Bricks Filter Hook tutorial, we can make use of some of the following useful functions that Bricks provides:

  • \Bricks\Query::is_looping() can help us check whether the element is currently inside query loop.
  • \Bricks\Query::get_loop_object_type() will return what the looping object type is, it could be post, term, user etc.
  • \Bricks\Query::get_loop_object_id() will return the current looping object Id.
  • \Bricks\Query::get_loop_object() will return the current looping object itself.

in a custom function that returns the current term’s slug and set the link URL to this function’s call within the loop.

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

// Function to get the current term slug
// Usage: 
function bl_get_term_slug() {
	if ( \Bricks\Query::is_looping() && \Bricks\Query::get_loop_object_type() === 'term' ) {
		$current_term = \Bricks\Query::get_loop_object();

		if ( $current_term->slug ) {
			return $current_term->slug;
		}
	}

	return false;
}

and set the URL (in this example) to:

Leave the first comment