Rj Umair
Rj Umair

Reputation: 1

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>

Upvotes: 0

Views: 3931

Answers (2)

Dipesh KC
Dipesh KC

Reputation: 3297

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 ;
   }
}

Upvotes: 1

Bojana Šekeljić
Bojana Šekeljić

Reputation: 1056

Here is the function:

<?php get_category_parents($cat); ?>

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

Upvotes: 0

Related Questions