Take a gander at the add_shortcode()
documentation and you'll see that the callback function is passed three parameters. The most important (and relevant to this) is the first $atts
parameter.
I would do something like this:
add_shortcode( 'parent-child', 'taxonomy_hierarchy' );
function taxonomy_hierarchy( $atts ){
$atts = shortcode_atts( array(
'link' => true,
'taxonomy' => 'property_city'
), $atts, 'parent-child' );
global $post;
$terms = wp_get_post_terms( $post->ID, $taxonomy );
/* You can pass conditions here to override
* the link var based on certain conditions. If
* it's a single post, current user is editor, etc.
*/
ob_start();
foreach( $terms as $term ){
if( $term->parent != 0 ){
$parent_term = get_term( $term->parent, $taxonomy );
echo (filter_var($atts['link'], FILTER_VALIDATE_BOOLEAN)) ? sprintf( '<a href="%s">%s</a>, ', esc_url( get_term_link($parent_term) ), $parent_term->name ) : "{$parent_term->name}, " ;
}
echo (filter_var($atts['link'], FILTER_VALIDATE_BOOLEAN)) ? sprintf( '<a href="%s">%s</a>', esc_url( get_term_link($term) ), $term->name ) : $term->name ;
}
return ob_get_clean();
}
This, using the shortcode_atts()
function allows you to set some default parameters for your shortcode. I've also set it so taxonomy
can be overwritten as well, which makes it much more extensible (for use later, in other projects, etc.)
I've changed the code slightly as well to use Output Buffering
since it's a bit faster and cleaner when dealing with Ternary Comparisons and outputs like this compared to string concatenation (imo).
What it does is check to see if the $link
attribute has been passed before determining to output the linked name, or just the name in plain text, and echoes the result into the output buffer.
This will allow you to get the following results:
[parent-child]
? <a href="#">New York</a>
? <a href="#">New York</a>, <a href="#">Manhattan</a>
[parent-child link="true"]
? <a href="#">New York</a>
? <a href="#">New York</a>, <a href="#">Manhattan</a>
[parent-child link="false"]
? New York
? New York, Manhattan
[parent-child link="false" taxonomy="some_other_taxonomy"]
? Top Level Term
? Top Level Term, Child Level Term
And so on. As I alluded to in the PHP comment, you can override the $link
boolean at any time before the foreach
loop, based on whatever conditions you want as well. So you can make the $link
always return true if is_single()
is true, or always return false if the current user isn't an editor, or anything else you can think of.
Documentation & Function Reference: