18th Jul '22
/
2 comments

[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:

Get access to all 610 Bricks code tutorials with BricksLabs Pro

2 comments

Leave a Reply to D Ee (Cancel Reply)

 

Related Tutorials..

Accessing ACF Repeater Sub Fields Programmatically in Bricks Query Loop

Accessing ACF Repeater Sub Fields Programmatically in Bricks Query Loop

It is possible to output sub field's values when a Bricks query loop's type has been set to a ACF Repeater without writing code. This…
Categories:
Pro
ACF Checkbox Sub Field as Unordered List in Bricks

ACF Checkbox Sub Field as Unordered List in Bricks

Updated on 22 Sep 2023 This Pro tutorial shows how the checked options of a Checkbox-type of Sub Field inside a ACF Repeater field can…
Categories: