I have inherited a website and the code I currently have seems to display the first category, judged by alphabetical order I think, on the post loop of a custom post…

I have this code that’s pulling through category name and the title of the post:

<div class="item__overlay <?php echo $overlay_class; ?>">
                    <span class="item__cat-title item__cat-title--overlay"><?php echo SeedHelpers::first_category($this->post_type); ?></span>
                    <h4 class="item__title"><?php the_title(); ?></h4>
                    <!--    <?php the_excerpt(); ?> -->
                    </div>
                </div> 

The bit of code you will notice is:

SeedHelpers::first_category($this->post_type)

This relates to a function, I believe, that will display the first of the category assigned to this post.

This function is here:

static function first_category($post_type = 'post') {
        if($post_type == 'post') {
            $category = get_the_category();

            if($category) {
                return $category[0]->cat_name;
            }

            return false;
        } elseif($post_type == 'portfolio') {
            $category = get_the_terms(get_the_ID(), 'portfolio-category');

            if($category) {
                return $category[0]->name;
            }

            return false;
        }
    }

Each of my posts have one main category and multiple child categories, I would like to alter the code so it shows the parent sub category only…

I have tried most things I have found online but I can’t seem to make it display properly…

Read more here: Show Parent Category instead of First Category – WordPress


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: