13

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)请帮助我

谢谢。

4

3 回答 3

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

于 2013-11-13T18:50:34.583 回答
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 
于 2014-01-11T17:20:55.700 回答
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 } } ?>
于 2018-03-16T09:31:41.833 回答