WordPress -如何获得父类别ID

2w3kk1z5  于 2022-12-17  发布在  WordPress
关注(0)|答案(5)|浏览(201)

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;

此代码回显单页cat名称

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

此chode回显cat名称的id

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

我需要回显父ID(cat_ID)请帮助我
谢谢。

i5desfxk

i5desfxk1#

很简单,非常简单。

//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

2wnc66cl

2wnc66cl2#

$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
z9zf31ra

z9zf31ra3#

对于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);
fjaof16o

fjaof16o4#

<?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 } } ?>
brjng4g3

brjng4g35#

我知道这是很久以前的问题了,但因为没有一个答案对我有效,所以我决定分享我所做的:

$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);

相关问题