【问题标题】:wordpress show current category child functionwordpress 显示当前类别子功能
【发布时间】:2019-04-07 00:06:33
【问题描述】:

wordpress 有功能the_category(''); 用于显示分配给当前帖子的所有类别,但我需要获取当前类别唯一的子项而不显示父项。

例如我的帖子有类别类别父 --> 类别子和 the_category; print :your post cat is : ( category parent , category child )

我需要 parint,你的 post cat 是 : (category child) 而不是显示 parent。

【问题讨论】:

  • 您的问题很难理解,请改写。
  • 不很简单,我需要在 wordpress 的循环单页中获取当前类别子项

标签: php wordpress


【解决方案1】:

使用get_the_category 函数,女巫将返回分配给帖子的所有类别(这意味着所有父母和孩子也是如此),因此您可以遍历它们并查看女巫一个是父母,女巫一个是孩子并打印出你的那个重新尝试获得。我建议你在你的主题函数文件中构建一个函数。


更新

例如,假设您想在 single.php 主题文件中显示子类别名称,因此您可以这样做:

<?php $child_category = post_child_category(get_the_ID()); ?>
<?php if ( $child_category ) echo $child_category->cat_name; ?>

为了让它工作,你需要在你的主题函数文件中定义post_child_category函数(如果你查看你的主题目录,你会看到一个functions.php文件,如果没有,那么你可以创建现在),因此您将添加以下内容:

if ( ! function_exists( 'post_child_category' ) )
{
    function post_child_category( $id = null )
    {
        if ( $id = null )
            return false;

        $categories = get_the_category( $id );
        if ( count($categories) > 0 )
        {
            return $categories[count($categories)-1];
        } else {
            return false;
        }
    }
}

更新

如果您想显示类别链接,您可以这样做:

<?php $child_category = post_child_category(get_the_ID()); ?>
    <?php if ( $child_category ) : ?>
        <a href="<?php echo get_category_link($child_category->cat_ID); ?>" title="<?php echo $child_category->cat_name;?>">
            <?php echo $child_category->cat_name;?>
        </a>
    <?php endif;?>

【讨论】:

  • 是的,我喜欢这种方式,但我不知道在你的主题函数文件中构建一个函数。
  • +1,get_the_category 应该比 wp_list_categories 更容易,你只需要测试 category_parent 属性
  • 哦!一点是问题,这对所有事情都是正确的,但是,这只是文本而不是链接,我想链接这个!
【解决方案2】:
<ul>    
<?php
        $blogCategoryID = "5"; // current category ID
        $childCatID = $wpdb->get_col("SELECT term_id FROM $wpdb->term_taxonomy WHERE parent=$blogCategoryID");
        if ($childCatID){
            foreach ($childCatID as $kid)
            {
                $childCatName = $wpdb->get_row("SELECT name, term_id FROM $wpdb->terms WHERE term_id=$kid");
                ?>
                <li><a href="<?php echo get_category_link( $childCatName->term_id ); ?>"><?php echo $childCatName->name; ?></a></li>
           <?php
            }
        }

    ?>
</ul>

【讨论】:

    【解决方案3】:

    【讨论】:

    • 我看到了这个页面,但这是通过 id 或名称获取类别,我需要获取当前类别
    • 你确定 wp_list_categories 会显示分配给帖子的类别吗?
    • 我的问题是隔离父母和孩子。
    【解决方案4】:

    这对我有用

    $catID=$wp_query->query_vars['cat'];
    $args = array('parent' => $catID);
    $categories = get_categories( $args );
    foreach($categories as $category) { 
        echo '<li><a href="' . get_category_link( $category->term_id ) . '"  ' . '>' . $category->name.'</a> </li> ';
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-06
      • 2014-03-01
      • 1970-01-01
      • 2020-07-28
      相关资源
      最近更新 更多