dav*_*all 3 wordpress search children categories
我有这个代码,它位于 search.php 页面上,并检索每个帖子的所有类别,并回显出指向第一个类别的链接:
$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> ';
Run Code Online (Sandbox Code Playgroud)
我需要做的是使用类似的代码,但它会获得数组中最儿童/最深的类别?
这是打印出来的数组:
[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
)
Run Code Online (Sandbox Code Playgroud)
如您所见,一个类别具有 parent->3,另一个类别具有 parent->0。如何使用上述查询仅打印出父级-> 3 的类别的链接?
它可能很简单,但它有点超出我的头脑。任何帮助将不胜感激!
谢谢
戴夫
在你的 theme/functions.php 文件中添加这个函数:
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];
}
Run Code Online (Sandbox Code Playgroud)
然后让我们说就像你在 theme/search.php 中的例子一样
$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;
Run Code Online (Sandbox Code Playgroud)
根据我的知识,没有其他方法可以通过 get_the_category() 对类别进行排序,但我可能会弄错,如果是这样,上面的代码将不是最好的做事方式。