I've created custom taxonomies on WordPress and I want to display the current post taxonomies on the post in a list.
I'm using the following code to display a custom taxonomy named "Job Discipline":
<ul>
<?php $args = array('taxonomy' => 'job_discipline'); ?>
<?php $tax_menu_items = get_categories( $args );
foreach ( $tax_menu_items as $tax_menu_item ):?>
<li>
Job Discipline: <a href="<?php echo get_term_link($tax_menu_item,$tax_menu_item->taxonomy); ?>">
<?php echo $tax_menu_item->name; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
That's just one of many taxonomies I want to list.
The problem is that the above code is displaying all the "Job Disciplines" which have at least one post and not the current post taxonomy.
How can I sort out this issue?
Here is a modified code from the Codex (see link below) that will display all the taxonomies of the current post with attached terms:
<?php
// get taxonomies terms links
function custom_taxonomies_terms_links() {
global $post, $post_id;
// get post by post id
$post = &get_post($post->ID);
// get post type by post
$post_type = $post->post_type;
// get post type taxonomies
$taxonomies = get_object_taxonomies($post_type);
$out = "<ul>";
foreach ($taxonomies as $taxonomy) {
$out .= "<li>".$taxonomy.": ";
// get the terms related to post
$terms = get_the_terms( $post->ID, $taxonomy );
if ( !empty( $terms ) ) {
foreach ( $terms as $term )
$out .= '<a href="' .get_term_link($term->slug, $taxonomy) .'">'.$term->name.'</a> ';
}
$out .= "</li>";
}
$out .= "</ul>";
return $out;
} ?>
This is used like this:
<?php echo custom_taxonomies_terms_links();?>
The output might look like this if the current post has the taxonomies country
and city
:
<ul>
<li> country:
<a href="http://example.com/country/denmark/">Denmark</a>
<a href="http://example.com/country/russia/">Russia</a>
</li>
<li> city:
<a href="http://example.com/city/copenhagen/">Copenhagen</a>
<a href="http://example.com/city/moscow/">Moscow</a>
</li>
</ul>
The original code example in the Codex:
http://codex.wordpress.org/Function_Reference/get_the_terms#Get_terms_for_all_custom_taxonomies
Hope this helps - I'm sure you can adapt this to your project ;-)
But what if I want to display only some of them and not all of them? Also, I would like to name them myself instead of it giving taxonomy names with underscores. Any idea how can I achieve that?
Here is one modification to achieve that:
function custom_taxonomies_terms_links() {
global $post;
// some custom taxonomies:
$taxonomies = array(
"country"=>"My Countries: ",
"city"=>"My cities: "
);
$out = "<ul>";
foreach ($taxonomies as $tax => $taxname) {
$out .= "<li>";
$out .= $taxname;
// get the terms related to post
$terms = get_the_terms( $post->ID, $tax );
if ( !empty( $terms ) ) {
foreach ( $terms as $term )
$out .= '<a href="' .get_term_link($term->slug, $tax) .'">'.$term->name.'</a> ';
}
$out .= "</li>";
}
$out .= "</ul>";
return $out;
}