Wordpress:get_the_category和echo out链接到最多/最深的类别

时间:2011-03-29 13:30:09

标签: wordpress search categories children

我有这个代码,它位于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-&gt; 3,另一个类别具有parent-&gt; 0。如何使用上述查询仅打印带有parent-&gt; 3的类别的链接?

它可能很简单,但它有点过头了。任何帮助将不胜感激!

由于

戴夫

1 个答案:

答案 0 :(得分:4)

在你的主题/ 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()对类别进行排序,但我可能会弄错,如果是这样,上面的代码就不是最好的处理方式。