WordPress - 如何获取父分类ID

14

WordPress - 如何获取父类别 ID


my category is  
news
---->sport news

我在体育新闻中发布了一篇文章。

当我进入体育新闻的文章时,如何获取父级(新闻) ID?

这段代码会输出父类别名称。

      foreach((get_the_category()) as $childcat) { $parentcat = $childcat->category_parent;  
echo get_cat_name($parentcat);
echo $parentcat->term_id;}   
        echo $post->post_parent->cat_ID; 

这段代码会输出单个页面的分类名称

   global $post;$category = get_the_category($post->ID);echo $category[0]->name;

这个chode回声猫的名称ID

        $category = get_the_category();    echo $category[0]->cat_ID; 

我需要回显父级ID(cat_ID),请帮忙。

谢谢。

5个回答

19

简单地说,非常简单。

//firstly, load data for your child category
$child = get_category(31);

//from your child category, grab parent ID
$parent = $child->parent;

//load object for parent category
$parent_name = get_category($parent);

//grab a category name
$parent_name = $parent_name->name;

学习get_category函数


它真的有效吗?get_category函数以post_id作为参数并返回category_id。因此,在下一个get_category函数中,它传递的是$parent,它是category_id的父ID而不是post_id。如果我错了,请纠正我。 - kodfire

9
$thiscat =  get_query_var('cat'); // The id of the current category
$catobject = get_category($thiscat,false); // Get the Category object by the id of current category
$parentcat = $catobject->category_parent; // the id of the parent category 

非常感谢您。 - Mansoorkhan Cherupuzha

1

针对 Wordpress 5.9 版本。

获取父级分类 ID:

$cat = get_queried_object();
$parentCatId = $cat->parent;

获取当前分类ID:

$cat = get_queried_object();
$catId = $cat->term_id

通过id获取分类名称:

$name = get_the_category_by_ID($catId);

0

我知道这个问题很久以前就被问过了,但因为没有一个答案适用于我,所以决定分享我所做的:

$post_id = 1000;
$category = get_category($post_id);

$category_parent_id = $category[0]->parent;

// It gets the name and not the id or the object
$category_name = get_the_category_by_ID($category_parent_id);

// And here is the parent of the category
$category_parent = get_category_by_path($category_name);

0
<?php 
    if (is_category()) 
    {
    $thiscat = get_category( get_query_var( 'cat' ) );
    $catid = $thiscat->cat_ID;
    $parent = $thiscat->category_parent;
    if (!empty ($catid) ) {
    $catlist = get_categories(
                                array(
                                'child_of' => $catid,
                                'orderby' => 'id',
                                'order' => 'ASC',
                                'exclude' => $parent,
                                'hide_empty' => '0'
                                ) );

        ?>
            <div class="subcat-list">
                <ul>
                    <?php foreach ($catlist as $category) { ?>
                      <li><a href="<?php echo get_category_link( $category->term_id ); ?>"><?php echo $category->name; ?></a></li>
                      <?php } ?> 
                 </ul>
            </div>
            <?php } } ?>

请在您的答案中添加解释,说明它是如何解决问题的。请提供更具体的上下文或要翻译的具体内容,以便我可以为您提供准确的翻译。 - Omar Einea

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接