WordPress:get_the_category并回显到最儿童/最深类别的链接 [英] Wordpress: get_the_category and echo out link to child-most/deepest category
问题描述
我有此代码,位于search.php页面上,它检索每个帖子的所有类别,并在第一个类别的回显中提供链接:
I have this code which is located on the search.php page and retrieves all the categories for each post and echo's out a link to the first category:
$category = get_the_category(); //print_r($category);
if ($category) {
echo '<a href="' . get_category_link( $category[0]->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category[0]->name ) . '" ' . '>' . $category[0]->name.'</a> ';
我需要做的是使用类似的代码,但要获得子级最大/最深的类别数组?
What I need to do is use a similar code but that gets the child-most/deepest category in the array?
这是打印出来的数组:
[0] => stdClass Object
(
[term_id] => 170
[name] => ACS Series Suspended & Crane Scales - EC Approved
[slug] => uwe-acs-series-suspended-crane-scales
[term_group] => 0
[term_taxonomy_id] => 170
[taxonomy] => category
[description] =>
[parent] => 3
[count] => 4
[object_id] => 1578
[cat_ID] => 170
[category_count] => 4
[category_description] =>
[cat_name] => ACS Series Suspended & Crane Scales - EC Approved
[category_nicename] => uwe-acs-series-suspended-crane-scales
[category_parent] => 3
)
[1] => stdClass Object
(
[term_id] => 3
[name] => Crane Scales
[slug] => crane-scales
[term_group] => 0
[term_taxonomy_id] => 3
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 53
[object_id] => 1578
[cat_ID] => 3
[category_count] => 53
[category_description] =>
[cat_name] => Crane Scales
[category_nicename] => crane-scales
[category_parent] => 0
)
您可以看到,一个类别的父级-> 3,另一个类别的父级-> 0。如何使用上面的查询仅打印出parent-> 3类别的链接?
As you can see, one category has parent->3 and the other has parent->0. How do I use the above query to print out the link only for a category with parent->3?
它可能很简单,但是有点让人头疼。任何帮助将不胜感激!
Its probably quite simple but its a bit over my head. Any help would be greatly appreciated!
谢谢
戴夫
推荐答案
在您的theme / functions.php文件中添加此功能:
Add this function in you're theme/functions.php file :
function get_deep_child_category( $categories )
{
$maxId = 0;
$maxKey = 0;
foreach ( $categories as $key => $value )
{
if ( $value->parent > $maxId )
{
$maxId = $value->term_id;
$maxKey = $key;
}
}
return $categories[$maxKey];
}
然后,假设您在theme / search.php中成为示例
Then let's say as in you're example in theme/search.php you do
$categories = get_the_category();
if ( $categories ) :
$deepChild = get_deep_child_category( $categories );
?>
<a href="<?php echo get_category_link( $deepChild->term_id ); ?>" title="<?php echo sprintf( __( "View all posts in %s" ), $deepChild->name ); ?>"><?php echo $deepChild->name; ?></a>
<?php
endif;
根据我的知识,没有其他方法可以通过get_the_category()对类别进行排序,但是我可能会误认为如果这样的话,上面的代码将不是最好的方法。
From my knoledge there is no other way of sorting categories thru get_the_category() but i might be mistaken and the code above wouldn't be the best way of doing things if so .
这篇关于WordPress:get_the_category并回显到最儿童/最深类别的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!