categories - Get parrent category name

I have 3 levels of categories:Cat 1- Cat 2- Cat 3-- Cat 4I want to add Parent category name after page title. For exa

I have 3 levels of categories:

Cat 1
- Cat 2
- Cat 3
-- Cat 4

I want to add Parent category name after page title. For example:

<h1>Cat 4</h1>
<p>From Cat3 in Cat 1</p>

But only for third level. Is it possible and what is the better way to do this correct?

I have fond a way to get Cat3, but I still bon't know, how to get previous category name and how to display the message for only third level.

$parent = get_queried_object()->parent;
if( $term = get_term_by( 'id', $parent, 'product_cat' ) ){
    echo '<span class="sub-cat">' . $term->name . '</span>';
}

Thanks!

I have 3 levels of categories:

Cat 1
- Cat 2
- Cat 3
-- Cat 4

I want to add Parent category name after page title. For example:

<h1>Cat 4</h1>
<p>From Cat3 in Cat 1</p>

But only for third level. Is it possible and what is the better way to do this correct?

I have fond a way to get Cat3, but I still bon't know, how to get previous category name and how to display the message for only third level.

$parent = get_queried_object()->parent;
if( $term = get_term_by( 'id', $parent, 'product_cat' ) ){
    echo '<span class="sub-cat">' . $term->name . '</span>';
}

Thanks!

Share Improve this question edited Jan 6, 2020 at 22:58 Alexander Goroshev asked Dec 5, 2019 at 21:26 Alexander GoroshevAlexander Goroshev 1446 bronze badges 1
  • Yes, it's possible. How to accomplish it depends on your theme. You would first want to create a child theme, then copy whichever file applies - could be category.php or archive.php - and then add your code. Once you verify you're in the right file, build out the logic that checks the current category to see if it has a parent and grandparent, but not a great-grandparent, and if so outputs that paragraph. – WebElaine Commented Dec 5, 2019 at 21:56
Add a comment  | 

1 Answer 1

Reset to default 0

You could have a category description. For example the Cat 4 will have the category description as : From Cat3 in Cat 1.

You add the category description when you edit the category inside of WP > Posts > Categories

Then to display the category description use this PHP code inside of your archive.php theme file:

<?php echo category_description(); ?>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744855376a4597372.html

相关推荐

  • categories - Get parrent category name

    I have 3 levels of categories:Cat 1- Cat 2- Cat 3-- Cat 4I want to add Parent category name after page title. For exa

    2天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信