how to display all categories in wordpress?

Clorge32 picture Clorge32 · Sep 26, 2016 · Viewed 72.7k times · Source

I used this code:

      $categories = wp_get_post_categories(get_the_ID());
      foreach($categories as $category){
          echo '<div class="col-md-4"><a href="' . get_category_link($category) . '">' . get_cat_name($category) . '</a></div>';
        }

but return only one category, how can i get all the categories?

Answer

Simon Pollard picture Simon Pollard · Sep 26, 2016

In the code you gave us you are selected the categories selected for the specific post get_the_ID() is doing that part. However you would be best off using another function get_categories() https://developer.wordpress.org/reference/functions/get_categories/ which you would do like so:

$categories = get_categories();
foreach($categories as $category) {
   echo '<div class="col-md-4"><a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a></div>';
}

You can also pass through arguments to be more specific (if needed) - see https://developer.wordpress.org/reference/functions/get_terms/ for details on what you can pass through