admin管理员组

文章数量:1431997

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.

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.

Share Improve this question edited Apr 19, 2019 at 16:29 fuxia 107k39 gold badges255 silver badges459 bronze badges asked Apr 19, 2019 at 15:29 barale61barale61 31 silver badge2 bronze badges 2
  • 1 Welcome to WPSE. Do you have a custom taxonomy created for your post type? – jdm2112 Commented Apr 19, 2019 at 15:40
  • yes, I have several – barale61 Commented Apr 19, 2019 at 17:14
Add a comment  | 

1 Answer 1

Reset to default 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/reference/functions/get_the_terms/

本文标签: categoriesTo display the category of a specific custom post type