Dev Notes

Software Development Resources by David Egan.

Display WordPress Term Links


Front End, WordPress
David Egan

Display a list of links to associated WordPress terms for a given taxonomy/custom taxonomy.

Two options for class methods to achieve this:

<?php
...

  /**
   * Output post term links.
   *
   * The `get_the_terms()` function returns an array of term objects for the
   * given taxonomy.
   *
   * @uses get_the_terms()
   * @param  string The custom taxonomy to target
   * @return string HTML markup for a list of term links
   */
  public function the_terms( $taxonomy = 'category' ) {

    $terms = get_the_terms( $this->post_ID, $taxonomy );

    ob_start();

    foreach ($terms as $key => $term) {

      echo '<a href="' . get_term_link($term) . '">' . $term->name . '</a>';
      echo ( $key !== count( $terms ) -1 ) ? ", " : NULL; // Comma separated, but not last item

    }

    echo ob_get_clean();

  }

  /**
   * Alternative method.
   *
   * The `wp_get_object_terms()` function retrieves the terms associated with
   * the given object(s) for the specified taxonomy.
   *
   * @uses wp_get_object_terms()
   * @param  string The custom taxonomy to target
   * @return string HTML markup for a list of term links
   */
  public function alt_post_terms( $tax = 'category' ) {

    $post_terms = wp_get_object_terms( $this->post_ID, $tax, array( 'fields' => 'ids' ) );

    if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) {

      $term_ids = implode( ',' , $post_terms );

      $terms = wp_list_categories(
        [
          'title_li' => '',
          'style'    => 'none',
          'echo'     => false,
          'taxonomy' => $tax,
          'include'  => $term_ids
        ]
       );

      $terms = rtrim( trim( str_replace( '<br />',  ',', $terms ) ), ',' );

      return $terms;

    }

  }

...

You could also simply drop this into the template, within the loop to return a list of links to ‘project-category’ terms for the current post:

<?= get_the_term_list( $post->ID, 'project-category', 'Project Categories: ', ', ' ); ?>

References


comments powered by Disqus