0

Thanks to wordpress.org, the snippet below will display a list child categories link only for each respective post if there's a child category for them.

<?php
  foreach((get_the_category()) as $category) {
    if ($category->category_parent  != 0) {
    echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . esc_attr(strip_tags($category->name)) . '" ' . '>' . $category->name.'</a> ';
    }
  }
?>

Now I'm looking for a different snippet that'll display a list of parent categories only. Anyway how to get the parent category only?

  • Just reverse the if logic - instead of checking it has a parent, check that it doesn't i.e. if ( ! $category->category_parent ) – TheDeadMedic Apr 16 '16 at 12:58
2

Try this:

$post = get_post(); // If $post is already available, skip.
$terms = get_the_terms( $post->ID, 'category' );
foreach ( $terms as $term ) :
    if ( $term->parent === 0 ) :
        echo '<a href="' . esc_url( get_term_link( $term->term_id, 'category' ) ) . 
            '" title="' . esc_html( $term->name ) . '" ' . '>' . esc_html( $term->name ) . 
            '</a> ';
    endif;
endforeach;

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.