Skip to content

Instantly share code, notes, and snippets.

@moxet
Last active August 17, 2023 06:28
Show Gist options
  • Save moxet/32e34740bec6c87e8ce35ac70202e660 to your computer and use it in GitHub Desktop.
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"]
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