我使用了这段代码:
$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>';
}
但只返回一个类别,我怎样才能获得所有类别?
答案 0 :(得分:20)
在您给我们的代码中,您选择了为特定帖子选择的类别,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/
答案 1 :(得分:2)
您还可以使用wp_list_categories并将参数传递给它以仅显示您需要的内容。可以在codex中找到完整的参数列表: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) );
答案 2 :(得分:0)
<?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>';
}