Only print the parent category (WordPress)

I am making a blog template for my theme.
But I have one problem…

If I post a post on my blog, I only want to display the parent category of that post.

Read More

So for example, if I post a post with this category hierarchy:
– Vacation
– France
– First Day

I only want that Vacation is displayed on my blog.

Does anyone know how to solve this problem?

Sincerely,
Joren

Related posts

2 comments

  1. <?php $parentscategory ="";
    
    foreach((get_the_category()) as $category) {
    if ($category->category_parent == 0) {
    
    $parentscategory .= ' <a href="' . get_category_link($category->cat_ID) . '" title="' . $category->name . '">' . $category->name . '</a>, ';
    
    }
    
    }
    
    echo substr($parentscategory,0,-2); ?>
    
  2. This code maybe useful for you:

    Display posts that have this category (and any children of that category), using category slug:

    $query = new WP_Query( 'category_name=Vacation' );
    

    Or

    $category_query_args = array(
        'category_name' => 'Vacation'
    );
    
    $category_query = new WP_Query( $category_query_args );
    

    Please try and let me know.

Comments are closed.