6

I want to get category id from post id of a custom type. I have the post id, but I can't get it's category id.

I have used so many codes but it doesn't work, may be due to custom post type.

$category = get_the_category( $post->ID );

Any suggestions?

3 Answers 3

10

wp_get_post_categories can only get POST categories not a custom post's categories, try this instead:

$category = get_the_terms( $post->ID, 'custom-taxonomy-here' );     
foreach ( $category as $cat){
   echo $cat->name;
}

Check this link

3

Are your custom post type supporting the standard category taxonomy? If the category used in your custom post type is a custom taxonomy and not the standard category taxonomy you should get_the_terms() instead of get_the_category().

$categories = get_the_terms($post->ID, "my-custom-taxonomy");
1
  • Hi @AmanEsfera!! If your question is resolved, please accept the answer by clicking in the "V" symbol at the left of the answer bellow the vote buttons. This will help other users find the correct answer quickly.
    – cybmeta
    May 5, 2014 at 7:26
1

this solution works for me:

    global $wpdb;

    // get all category id's based on post id
    $result = $wpdb->get_results( " select term_taxonomy_id from " . $wpdb->prefix . "term_relationships where object_id = '" . $post_id . "' " );
    $cats_ids_array = [];
    foreach ( $result as $c ) {
        $cats_ids_array[] = $c->term_taxonomy_id;
    }

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.