john-marcello
john-marcello

Reputation: 265

Get top-level category and make it a link

Wordpress - Trying to get the top-level parent category name and make it a link

Categories are structured as

Europe > Eastern Europe > Poland

In this instance I wan to get the cat name for Europe and make it a link to the cat page for Europe.

No matter what I try I do not seem to be able to get the top most category. This is being executed in a custom QP Query

Upvotes: 0

Views: 776

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64486

Here you go

Get only top level categories

<?php
$args = array(
  'orderby' => 'name',
  'parent' => 0
  );
$categories = get_categories( $args );
foreach ( $categories as $category ) {
    echo '<a href="' . get_category_link( $category->term_id ) . '">' . $category->name . '</a><br/>';
}
?>

Get top level categories / taxonomy

<?php
$args = array(
    'type'          => 'post',
    'orderby'       => 'term_group',
    'hide_empty'    => 0,
    'hierarchical'  => 0,
    'parent'        => 0,
    'taxonomy'      => '..if you are using a taxonomy instead of a category'
);
get_categories( $args ); 
?>

Upvotes: 1

Related Questions