Home Forums General Issues Get category parent for post only


Get category parent for post only

  • Hi, I am working with a custom category taxonomy field named ‘category-tax’, that returns Term ID. Having a tough time figuring out how to get the parent category returned, when the parent category is designated in the post. It seems I am only getting the parent category returned when the child category is designated.

    I am working with what appears to be non-native ACF code, it sort of functions with this exception but would like to clean this up so it works as intended. Wondering if anyone could shed some light on how to sort this out?

    function getCategoryButtons() {
        $postCategories = get_the_category($postID);
        $postHTML .= '<div class="buttons">';
        if ($postCategories[0]->parent != 0) {
            $cat = get_category($postCategories[0]->parent);
            $postHTML .= '<a href="'.get_category_link($cat->cat_ID).'">'.$cat->name.'</a>';
        $postHTML .= '</div>';
        return $postHTML;

    If I copy and paste in the following code which I copied and pasted from the ACF site, it returns all parent and child categories so I know the field is working.

        $terms = get_terms( 'category' );
     if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
         echo '<ul>';
         foreach ( $terms as $term ) {
           echo '<li>' . $term->name . ' - ' . get_field('short_description', $term->taxonomy . '_' . $term->term_id) . '</li>';
         echo '</ul>';
Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.