Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only parent categories wordpress

Tags:

php

wordpress

i'm trying to create a category list, but i only want to list the parent categories and not the child categories. How can i do this? so far i've created a list, which list all parent and child categories.

function categoryList() {


  $args = array(
  'orderby' => 'name',
  'order' => 'ASC'
  );
$categories = get_categories($args);

  $output .= '<ul class="category-list">';
  foreach($categories as $category) { 
          if ($category){
          $output .= '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>';
          }
  } 

  $output .= '</li>';
  $output .= '</ul>';

  return $output;

}
like image 220
Peter Pik Avatar asked Dec 05 '22 23:12

Peter Pik


1 Answers

By parent categories, I assume you mean top-level categories. This is actually documented on the Codex page for get_categories: You should call get_categories with parent => 0

$args = array(
  'orderby' => 'name',
  'order' => 'ASC',
  'parent' => 0
);
$categories = get_categories($args);
like image 137
vicvicvic Avatar answered Dec 12 '22 00:12

vicvicvic