如何查看wordpress属于哪个级别类别?
让我告诉你这个场景,首先说wordpress中类别的结构是这样的
Level 1: Top
Level 2: -Nextme_1
Level 3: --Nextme_2
--Nextme_3
Level 4: ---Nextme_4
---Nextme_5
,现在我需要检查类别的级别是多少?假设我捕获了 3 级类别,那么我必须使用不同的模板,如果是 4 级。那么我需要使用另一个模板?
有人可以给我一些提示吗?
谢谢
拉胡尔
Let me tell you the scenario first say the structure of the categories in wordpress is like this
Level 1: Top
Level 2: -Nextme_1
Level 3: --Nextme_2
--Nextme_3
Level 4: ---Nextme_4
---Nextme_5
Now I require to check what is the level of the category? Say I catch a category of level 3 so I have to use different template and if its level 4. Then I need to use another template?
Anybody can give me some hint?
Thanks
Rahul
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您没有很多类别,您可以尝试从管理员编辑它们的 slug,然后在您的页面中,您可以通过以下方式获得类别 slug:
现在,当您编辑类别 slug 时,请尝试按照其级别命名它们:cat- 1级,2级猫。然后在您的页面中,使用某些 php 字符串函数从类别 slug 中提取数字,然后检查该数字:
等等。
稍后编辑:
试试这个:
If you don't have many categories you can try to edit their slug from admin, and then in your page you get the category slug this way:
Now, when you're editing the categories slugs try naming them after their level: cat-lvl-1, cat-lvl-2. Then in your page you extract the number from category slug using some php string function, and then you check that number:
and so on.
Later edit:
Try this:
您可以调用 get_ancestors() 函数来获取
包含父项的数组给定对象
。然后您需要对结果中的元素进行计数。You can call the get_ancestors() function to get
an array containing the parents of the given object
. Then you need to count elements in the result.多谢。这是极好的,只需稍加更改即可,您编写的代码很好,但它没有返回任何值(即 $level),尽管它的计算正确。我做了一个小小的改变,现在只需对下面给出的代码进行一些轻微的编辑,它就可以正常工作了
。``
谢谢
@zuzuleinen
Thanks a lot. This is superb with slight a change the code that you have written is fine but its not returning any value.(i,e the $level) although its calculating correct. A minor change i did and its work fine now with a slight editing of you code given below..
`
`
Thanks @zuzuleinen
几个月前我访问过这个页面。我今天回来了,上面的解决方案上有向上的箭头,然后仍然继续挖掘。尽管这是一个很好的解决方案,但 WordPress 通常提供更好或接近的解决方案。
get_category_parents()
该函数基本上按照 Rahul 的输入进行操作。它也称自己,这似乎是最合乎逻辑的方法,这就是为什么拉胡尔在这方面从我那里得到了一个观点。不要使用 $link,返回一个类别字符串,explode() 它们然后计数,或者我想我们可以计算分隔符被使用的次数并添加 1。
}
I visited this page months back. I came back today, arrow up on the above solution then still went digging. Although it is a good solution, Wordpress often offers better or close.
get_category_parents()
This function does as Rahul has typed basically. It also calls itself which seems the most logical approach and that is why Rahul gets a point from me on this. Do not use $link, return a string of categories, explode() them then count or I suppose we could count the number of times the separator has been used and add 1.
}