Blog / WordPress/ WordPress Custom Taxonomies: Complete Guide to Get Term Names and Links

WordPress Custom Taxonomies: Complete Guide to Get Term Names and Links

WordPress 自定义分类法:获取分类名称与链接的完整指南

Core Concepts and Important Notes

Custom taxonomies allow you to create classification systems for posts or custom post types separate from the default 'Categories' and 'Tags'. For example, you can create 'Genre', 'Director', and 'Actor' taxonomies for a 'Movie' post type.

Important: The following methods primarily apply when using both custom post types and custom taxonomies. If you use a custom taxonomy on the default 'post' type, you might encounter a '404 page not found' error when trying to access term links. This happens because WordPress's default permalink rules may not generate correct rewrite rules for this combination. Usually, you need to resolve this by flushing rewrite rules (e.g., using flush_rewrite_rules()) or re-saving permalink settings in the admin panel.

Code Implementation to Get Custom Taxonomy Names and Links

Here is a robust function example that retrieves a post's custom taxonomy terms, intelligently distinguishes between parent and child terms, and outputs term names with correct links. We'll use the custom post type movie and its taxonomy types as an example.

Step 1: Add the Function to Your Theme

Place the following code in your current theme's functions.php file.

/**
 * Get hierarchical custom taxonomy links for a post.
 *
 * @param int    $post_id    Post ID, defaults to current post.
 * @param string $taxonomy   Custom taxonomy name.
 * @param string $separator  Separator between multiple child terms.
 * @param bool   $echo       Whether to echo output or return string.
 * @return string|void       HTML string of term links, or echoes.
 */
function get_taxonomy_hierarchy_links( $post_id = null, $taxonomy = 'types', $separator = ', ', $echo = true ) {
    if ( null === $post_id ) {
        global $post;
        if ( ! $post ) return '';
        $post_id = $post->ID;
    }

    $terms = wp_get_post_terms( $post_id, $taxonomy );
    if ( is_wp_error( $terms ) || empty( $terms ) ) return '';

    $output = '';
    $parent_term = null;
    $child_terms = array();

    foreach ( $terms as $term ) {
        if ( 0 == $term->parent ) {
            $parent_term = $term;
        } else {
            $child_terms[] = $term;
        }
    }

    if ( $parent_term ) {
        $parent_link = get_term_link( $parent_term, $taxonomy );
        if ( ! is_wp_error( $parent_link ) ) {
            $output .= sprintf( '%s', esc_url( $parent_link ), esc_html( $parent_term->name ) );
        }
    }

    if ( ! empty( $child_terms ) ) {
        $child_links = array();
        foreach ( $child_terms as $child_term ) {
            $child_link = get_term_link( $child_term, $taxonomy );
            if ( ! is_wp_error( $child_link ) ) {
                $child_links[] = sprintf( '%s', esc_url( $child_link ), esc_html( $child_term->name ) );
            }
        }
        if ( ! empty( $child_links ) ) {
            if ( $parent_term ) $output .= ' / ';
            $output .= implode( $separator, $child_links );
        }
    }

    if ( $echo ) {
        echo $output;
    } else {
        return $output;
    }
}

Step 2: Call the Function in Your Theme Template

Insert the following call where you want to display the term names and links (e.g., in single-movie.php or content-single.php).

<div class="movie-taxonomy-types">
    <span class="label">Genre: </span>
    <?php get_taxonomy_hierarchy_links( null, 'types' ); ?>
</div>

Code Explanation and Optimizations

  • Function Encapsulation: The functionality is packaged into a reusable function with clear parameters, improving flexibility and maintainability.
  • Error Handling: Uses is_wp_error() to check returns from wp_get_post_terms() and get_term_link(), preventing page errors if terms or links are missing.
  • Security: Escapes output with esc_url() and esc_html() to prevent XSS vulnerabilities.
  • Clear Logic: Separates parent and child term handling. Output format is "Parent Term / Child Term 1, Child Term 2".
  • Return Option: The $echo parameter lets you choose to echo the result directly or return it as a string for further processing.

Using this method, you can reliably display names and links for any custom taxonomy in your WordPress theme, supporting both single-level and hierarchical term structures.

Post a Comment

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