Get terms with a parent

With the following function you can return only the terms with a parent term (so are child terms), by post id and taxonomy. Notice that there terms also can be parents when using multiple levels of hierarchy.

/**
 * Returns terms with parents of a post
 *
 * @param int $post_id the post
 * @param mixed $taxonomy to get terms from specific taxonomy
 */
function get_terms_with_parent( $post_id, $taxonomy ) {
    if ( empty( $post_id ) ) {
        global $post;
        $post_id = $post->ID;
    }
    $terms = wp_get_post_terms( $post_id, $taxonomy );
    foreach ( $terms as $key => $term ) {
        if ( $term->parent != 0 ) {
            $new_terms[] = $term;
        }
    }
    return $new_terms;
}

Leave a reply

Feel free to ask questions or make comments.

Comments

    No comments yet..