3

WordPress 如何获得最顶级的自定义分类

 2 years ago
source link: https://www.ixiqin.com/2022/02/19/how-to-get-top-level-tax/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

WordPress 支持设定多级分类,如果你需要在页面中展示最顶级的分类,则需要获取到最顶级的分类,具体实现的方式如下:

1. 获取当前文件类型的自定义分类

使用如下代码获取到自定义分类

$tax = wp_get_post_terms($post->ID,array('part'))

获得的结果如下

Array
(
    [0] => WP_Term Object
        (
            [term_id] => 7
            [name] => 目录1
            [slug] => category1
            [term_group] => 0
            [term_taxonomy_id] => 7
            [taxonomy] => part
            [description] => 
            [parent] => 6
            [count] => 2
            [filter] => raw
        )

)

这里的 term_id 则代表你设定的自定义分类的 ID

2.获取分类树

因为分类是多级的,我们需要找到祖先节点,因此需要用到函数 get_ancestors ,执行如下代码

$tree = get_ancestors($tax[0]->term_id)

会获得如下结果

Array
(
    [0] => 6
    [1] => 8
)

这个返回结果则是从你当前分类向上查找,查找到最顶级的分类的结果。需要注意的是,这个数组的最后一个元素才是你最终最顶级的分类。

3. 提取最后一个元素的 ID

当你知道了最后一个才是最顶级的分类,只需要使用 end() 函数来获取最后一个。

end($tree)

这样,就能拿到最终目录的 ID,接下来要做的就是在你的界面上展示这些数据。

本条目发布于2022年2月19日。属于WordPress分类,被贴了 WordPress 标签。

← 为 WordPress 加入 Server Timing 判断不同行为性能差异 Gutenberg 编辑器带来的模式变更 →

发表评论 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

评论 *

显示名称 *

电子邮箱地址 *

网站地址

在此浏览器中保存我的显示名称、邮箱地址和网站地址,以便下次评论时使用。

如果有人回复我的评论,请通过电子邮件通知我。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK