0

I apologize for my English, but I am French. In my custom search page I display the results of my custom post type and everything is good. Only, I would like to display above the custom post type the category that is his. To display the post categories I do:

$category = get_the_category ();
echo "<p> Category:". $category[0]->cat_name. "</ p>";

But how to do for custom post type?
Thank you for your help.

  • 1
    Welcome to WPSE. Do you have a custom taxonomy created for your post type? – jdm2112 Apr 19 at 15:40
  • yes, I have several – barale61 Apr 19 at 17:14
0

For a custom post type, use get_the_terms() instead:

<?php $post_terms = get_the_terms( get_the_ID(), 'your-taxonomy' ); ?>
<p> Category: <?php echo $post_terms[0]->name; ?></p>

Much like the results from get_the_category, the returned value of get_the_terms() is an array of term objects for the taxonomy that you specify when calling the function. In the example code, that is "your-taxonomy".

This sample code will only display the first term if multiple terms are assigned to a post. That is the 'zero position' in the array. Any subsequent terms would be returned in $post_terms[1], $post_terms[2], etc

https://developer.wordpress.org/reference/functions/get_the_terms/

  • 1
    Super it works! I will look for "get_the_term" Thank you so much. – barale61 Apr 22 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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