D
D
Denis Valerievich2021-03-19 11:17:58
Taxonomy
Denis Valerievich, 2021-03-19 11:17:58

How to insert first subcategory with link in wordpress article?

Hello! I want to add a display of the first subcategory along with a link to it in the Wordpress article template. For example, I want to display the PARKS subcategory under the ATTRACTIONS category. But if there are no subcategories, then display the parent.

I've looked at a bunch of sites but haven't found anything yet. I came across a more or less suitable code, but it displays all categories and subcategories from the article. Tell me what needs to be changed so that only the first subcategory is displayed? Thank you!

$categories = get_the_category();
foreach ($categories as $cat) {
   $category_link = get_category_link($cat->cat_ID);
   echo '<a href="'.esc_url( $category_link ).'" title="'.esc_attr($cat->name).'">'.$cat->name.'</a>';
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Zolin, 2021-03-19
@NeXan87

Just take the first category from the array and output

$categories = get_the_category();
$cat = $categories[0];
$category_link = get_category_link($cat->cat_ID);
echo '<a href="'.esc_url( $category_link ).'" title="'.esc_attr($cat->name).'">'.$cat->name.'</a>';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question