gpt4 book ai didi

Wordpress:get_the_category 并回显指向子级最深/最深类别的链接

转载 作者:行者123 更新时间:2023-12-01 13:01:46 25 4
gpt4 key购买 nike

我有这个位于 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> ';

我需要做的是使用类似的代码,但该代码获取数组中的子级最深/最深的类别?

这是打印出来的数组:

[0] => stdClass Object
(
[term_id] => 170
[name] => ACS Series Suspended &amp; 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 &amp; 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
)

如您所见,一个类别有 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];
}

然后让我们假设您是 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;

根据我的知识,没有其他方法可以通过 get_the_category() 对类别进行排序,但我可能错了,如果是这样,上面的代码将不是最好的处理方式。

关于Wordpress:get_the_category 并回显指向子级最深/最深类别的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5473310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com