Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to display all categories in wordpress?

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?

like image 576
Clorge32 Avatar asked Sep 26 '16 13:09

Clorge32


3 Answers

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

like image 159
Simon Pollard Avatar answered Oct 16 '22 22:10

Simon Pollard


like this :

<?php
$categories = get_categories( array(
    'orderby' => 'name',
    'order'   => 'ASC'
) );

foreach( $categories as $category ) {
 echo '<div class="col-md-4"><a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a></div>';   
} 
like image 23
WordpressDave Avatar answered Oct 16 '22 21:10

WordpressDave


You can also use wp_list_categories and pass arguments to it to show only what you need. A full list of arguments can be found in the codex: https://developer.wordpress.org/reference/functions/wp_list_categories

This will output all categories (even if they're empty) indented to indicate hierarchy.

$args = array(
    'child_of'            => 0,
    'current_category'    => 0,
    'depth'               => 0,
    'echo'                => 1,
    'exclude'             => '',
    'exclude_tree'        => '',
    'feed'                => '',
    'feed_image'          => '',
    'feed_type'           => '',
    'hide_empty'          => 0,
    'hide_title_if_empty' => false,
    'hierarchical'        => true,
    'order'               => 'ASC',
    'orderby'             => 'name',
    'separator'           => '<br />',
    'show_count'          => 0,
    'show_option_all'     => '',
    'show_option_none'    => __( 'No categories' ),
    'style'               => 'list',
    'taxonomy'            => 'category',
    'title_li'            => __( 'Categories' ),
    'use_desc_for_title'  => 1,
);

var_dump( wp_list_categories($args) );
like image 7
Josh Bradley Avatar answered Oct 16 '22 21:10

Josh Bradley