Display a custom taxonomy list as links for a post

If you create a custom post types, chances are that you may also include creating custom taxonomies.  There may be times when you want to display these custom taxonomies in an isolated fashion away from other taxonomies.

This snippet of code allows you to pass in a POST_ID along with the keyname of a custom taxonomy.  The routine then queries the WordPress database to retrieve all taxonomies of the passed type that are assigned to the past post id.  The routine then continues by displaying the taxonomies in a nice clean list for visual display.

 * @param $post_id int          The post ID to get the terms for
 * @param $taxonomy string      The taxonomy type to the get the terms for
 * @return string               The string ready for output with links and taxonomy terms
function get_taxonomy_terms_as_links($post_id, $taxonomy){

    // Call for the list of taxonomies to be used
    $taxonomies = get_the_terms($post_id, $taxonomy);

    // Validate we have data

        // Iterate through each taxonomy, create a link and add it to our list
        $taxonomy_list = array();
        foreach($taxonomies as $taxonomy){
                $taxonomy_list[$taxonomy->name] = '<a href="'.get_term_link($taxonomy).'">'.$taxonomy->name.'</a>';
                // Not a valid taxonomy object

        // Sort the terms alphabetically

        // Create a single string
            return implode($taxonomy_list, ', ');

    // Return nothing if we are here
    return '';


// Example getting the built in tags for post id 350
echo get_taxonomy_terms_as_links(350, 'post_tag');
Posted in and tagged , , .