How to get the parent terms of any taxonomy

A post may have many taxonomies and each taxonomy may have also many terms and then each term may have many sub-terms.

What happens when you want to display a list of your terms with the links? And also, if showing all of them may be too much. A better choice will be to display only the parent terms. That’s cool, but WP does not contain a function for this.

So here we go:


function zerowp_get_parent_terms($taxonomy = 'category')
{
    $currentPost = get_post();
    $terms       = get_the_terms($currentPost->ID, $taxonomy);

    if (is_wp_error($terms)) {
        /** @var \WP_Error $terms */
        throw new \Exception($terms->get_error_message());
    }

    $map = array_map(
        function ($term) use ($taxonomy) {
            return '<a href="' . esc_url(get_term_link($term->term_id,
                    $taxonomy)) . '" title="' . esc_attr($term->name) . '">
                ' . $term->name . '
                </a>';
        },
        array_filter($terms, function ($term) {
            return $term->parent == 0;
        })
    );

    return implode(', ', $map);
}

Example usage:

This function can be called on the single post page.

Get the default categories for built-in post type:

echo zerowp_get_parent_terms(); // The default value on first arg is 'category', so we can ignore it.

Get the default tags for built-in post type:

echo zerowp_get_parent_terms('post_tag');

Get a custom taxonomy:

echo zerowp_get_parent_terms('my_custom_tax_name');
Member since January 2, 2019

Fullstack Web Developer with more than 12 years of experience in web development. Adept in all stages of advanced web development. Knowledgeable in the user interface, backend, testing, and debugging processes. Bringing forth expertise in design, installation, testing, and maintenance of web systems. Working exclusively and professionally with WordPress since 2010.

Comments

    Your email address will not be published. Required fields are marked *