1

I have a custom post type and a taxonomy which allows the user to select which category the post is in.

Here is my custom taxonomy:

add_action( 'init', 'create_talcat_taxonomy', 0);
function create_Talcat_taxonomy()
{
    register_taxonomy ( 'Talcat', 'artist', array( 'hierarchical' =>
    true, 'label' => 'Categories', 'query_var' => true, 'rewrite' => true )
);
}

On my homepage I am querying the post_type=artist , which works fine and brings in my artist posts. However how can I print/display the name of the category that post belongs to and then link to that category page?

2 Answers 2

2

I think you are talking about terms, not categories. You can use wp_list_categories to retrieve and display the terms that a post belongs to.

Here is a working example from the codex. Remember the $taxonomy variable can be changed to category or any custom taxonomy

<?php
$taxonomy = 'YOUR TAXONOMY NAME';

// get the term IDs assigned to post.
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
// separator between links
$separator = ', ';

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

   $term_ids = implode( ',' , $post_terms );
   $terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids );
   $terms = rtrim( trim( str_replace( '<br />',  $separator, $terms ) ), $separator );

    // display post categories
 echo  $terms;
}
?>

Just a tip, don't use capital letters in your taxonomy name when registering it. It does lead to problems most of the time

2
  • This causes an error of syntax error, unexpected '>' on the line that says &post_terms. Jul 24, 2014 at 11:16
  • Sorry, you are right about the syntax error. I posted that from my phone and for some reason it broke one of the single arrow. Corrected it Jul 24, 2014 at 15:56
5

I have managed to find a clean and simple way to achieve printing the taxonomy term assigned to the post with the following:

<?php the_terms( $post->ID, 'TAXONOMY NAME', ' ', ' / ' ); ?>

Using term retrieves the terms associated with the given object(s), in the supplied taxonomies.

Here is a link to the codex with examples and further detail.

2
  • I have to wait 2 days until I can accept it unfortunately. Jul 24, 2014 at 13:10
  • No problem, don't forget to come back in two days. Unfortunately it is how the system works Jul 24, 2014 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.