I recently spent a bit of time trying to determine how to get the categories of a custom post type, I though that it would be very easy and if I had known the function below it probably would have done.
I was extending a testimonials widget and wanted to filter the testimonials by a selected category, so whilst in the loop I wanted to see if this product was associated to a predefined category within the custom post type (testimonials in this case). Below shows you how I did it, the function that you need to find this is wp_get_post_terms()
//$test_n_cat is the category we are looking to match
//$showEnt is whether to show this entry in the loop
$showEnt = true;
if($test_n_cat) {
$term_list = wp_get_post_terms(get_the_ID(), 'category-testimonial',
array("fields" => "all"));
$showEnt = false;
//check to see what cat the post is in
foreach($term_list as $t){
if($t->term_id == $test_n_cat){
$showEnt = true;
}
}
}
if($showEnt){
//now show the testimonial
}
Here $test_n_cat is the category that I am looking to match. There maybe other ways to achieve this but this is working well for me, I hope this helps.
Leave A Comment