Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wordpress:get_the_the_category and echo out链接至child most/deep category_Wordpress_Search_Categories_Children - Fatal编程技术网

Wordpress:get_the_the_category and echo out链接至child most/deep category

Wordpress:get_the_the_category and echo out链接至child most/deep category,wordpress,search,categories,children,Wordpress,Search,Categories,Children,我在search.php页面上找到了这段代码,它检索了每篇文章的所有类别,echo提供了指向第一个类别的链接: $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 %

我在search.php页面上找到了这段代码,它检索了每篇文章的所有类别,echo提供了指向第一个类别的链接:

    $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> ';
如您所见,一个类别具有父级->3,另一个类别具有父级->0。如何使用上述查询仅打印父级->3的类别的链接

这可能很简单,但有点让我不知所措。任何帮助都将不胜感激

谢谢


Dave

在您的主题/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;
$categories=获取类别();
如果($类别):
$deepChild=get\u deep\u child\u category($categories);
?>
$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;