Last active
August 17, 2023 06:28
-
-
Save moxet/32e34740bec6c87e8ce35ac70202e660 to your computer and use it in GitHub Desktop.
Return Flat Terms with Levels from Shortcode [jet_post_terms tax="your-taxonomy" lvl="2"]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_shortcode( 'jet_post_terms', function( $atts = array() ) { | |
$atts = shortcode_atts( array( | |
'tax' => '', | |
'lvl' => '' | |
), $atts, 'jet_post_terms' ); | |
$post_id = get_the_ID(); | |
if ( empty( $atts['tax'] ) ) { | |
return; | |
} | |
$lvl = absint($atts['lvl']); | |
$result = array(); | |
$terms = wp_get_post_terms( $post_id, $atts['tax'], array( 'orderby' => 'parent' ) ); | |
if ( ! empty( $terms ) ) { | |
foreach ( $terms as $term ) { | |
$ancestors = get_ancestors( $term->term_id, $atts['tax'] ); | |
$term->ancestors = $ancestors; | |
$term->depth = count( $ancestors ) ; | |
if($term->depth === $lvl) | |
{ | |
$result[] = $term->name; | |
} | |
} | |
} | |
return implode(' ', $result ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment