如何在wordpress中显示所有类别?

how to display all categories in wordpress?

我使用了这个代码:

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

但是return只有一个类别,我怎样才能得到所有的类别?

像这样:

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

在您提供给我们的代码中,您选择了为特定 post 选择的类别 get_the_ID() 正在执行该部分。但是,您最好使用另一个函数 get_categories() https://developer.wordpress.org/reference/functions/get_categories/,您会喜欢这样做:

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

您还可以传递更具体的参数(如果需要)- 有关您可以传递的内容的详细信息,请参阅 https://developer.wordpress.org/reference/functions/get_terms/

您也可以使用 wp_list_categories 并向其传递参数以仅显示您需要的内容。可以在手抄本中找到完整的参数列表:https://developer.wordpress.org/reference/functions/wp_list_categories

这将输出缩进的所有类别(即使它们是空的)以指示层次结构。

$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) );