如何在WordPress发布循环中仅显示子类别

In our previous post, we shared how you can only display parent category in your WordPress Post Loop. This article is the continuation of the similar technique except here we will try to only show child category in your WordPress loop. Unfortunately the_category() does not have any optional parameters like child=0 or depth=-1. When creating our WordPress Gallery, this was one of the issues we had to deal with to organize our single site pages the way we wanted.

在上一篇文章中,我们分享了如何仅在WordPress Post Loop中显示父类别 。 本文是类似技术的延续,只是在这里我们将尝试仅在WordPress循环中显示子类别。 不幸的是, the_category()没有任何可选参数,例如child = 0或depth = -1。 在创建WordPress画廊时 ,这是我们要以所需方式组织单个站点页面时必须解决的问题之一。

To display only Child Category in the post loop (mostly single.php), all you have to do is replace the following code:

要在发布循环中仅显示子类别(主要是single.php),只需替换以下代码即可:

<?php the_category(', '); ?>

with this code:

使用此代码:

<?php
foreach((get_the_category()) as $childcat) {
if (cat_is_ancestor_of(10, $childcat)) {
echo '<a href="'.get_category_link($childcat->cat_ID).'">';
 echo $childcat->cat_name . '</a>';
}}
?>

Remember to change the number 10 to your parent category’s ID.

切记将数字10更改为父类别的ID。

In our gallery’s case, we had the parent category called Theme Framework, and bunch of child categories. Each post was only going to be assigned one child category for the framework (for example Genesis). So this code worked out perfectly. See the live example by clicking the image below:

在我们画廊的情况下,我们有一个名为“主题框架”的父类别,以及一堆子类别。 每个帖子仅将被分配给该框架的一个子类别(例如Genesis)。 因此,这段代码完美地完成了。 通过单击下面的图像查看实时示例:

Display Only Parent Category in Your WordPress Loop

Hope this trick solves your problem as well.

希望这个技巧也能解决您的问题。

Reference:

参考:

WordPress Codex

WordPress Codex

翻译自: https://www.wpbeginner.com/wp-themes/how-to-display-only-child-category-in-your-wordpress-post-loop/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值