简体   繁体   中英

how to get parent category id in wordpress

how to get only parent category ids. not children category ids i tried this code before which is showing me all ids of categories

 <?php  $category_ids = get_all_category_ids();

 foreach($category_ids as $cat_id) {
  $cat_name = get_cat_name($cat_id);
  //echo '<span class="png_bg category_icon"></span>' . $cat_name ;
?>
            <option><?php echo '<span class="png_bg category_icon"></span>' . $cat_name ; ?></option>
   <?php
 }
   ?>          
            </select>

There can be done in a number of ways. One of them is

$categories = get_categories();
foreach ($categories as $cat)
{
  // if it is a topmost category , it has no parents, ie parent=0
  if($cat->parent < 1)
  {
    echo $cat->category_nicename
    echo $cat->cat_name ;
   }
}

Here is the function:

<?php get_category_parents($cat); ?>

This function accepts several arguments, you can find the full reference on wordpress codex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM