通过Wordpress类别与foreach循环
问题描述:
我想这肯定是一个新手问题,但我试图修改在其他问题上找到的一些代码,我仍然无法找到如何循环通过类别的职位,并使他们显示为Bootstrap 4徽章。通过Wordpress类别与foreach循环
if (! function_exists('mytheme_the_categories')) :
/**
* Prints HTML with the categories, formatted as Bootstrap 4 badges.
*/
function mytheme_the_categories() {
$categories_list = get_the_category_list();
if ($categories_list && positor_categorized_blog()) {
echo '<div class="entry-categories"><span class="sr-only">'. esc_html__('Posted in ', 'positor') . '</span>';
foreach ($categories_list as $category) {
echo '<span class="badge badge-primary">';
echo $category->name;
echo '</span>';
}
echo '</div>';
}
}
endif;
但是得到一个错误: “警告:的foreach提供了无效的参数()”
答
的解决方案是使用get_the_category()
。粘贴下面的工作代码,以备日后任何人使用Google搜索。
if (! function_exists('mytheme_the_categories')) :
/**
* Prints HTML with the categories, formatted as Bootstrap 4 badges.
*/
function mytheme_the_categories() {
$categories_list = get_the_category();
if ($categories_list && positor_categorized_blog()) {
echo '<div class="entry-categories"><span class="sr-only">'. esc_html__('Posted in ', 'positor') . '</span>';
foreach ($categories_list as $category) {
echo '<span class="badge badge-primary mr-1">';
echo $category->name;
echo '</span>';
}
echo '</div>';
}
}
endif;
答
get_the_category_list()实际上生成HTML列表。
尝试使用get_categories()代替。
请参考https://developer.wordpress.org/reference/functions/get_the_category_list/,https://developer.wordpress.org/reference/functions/get_categories/
答
你可以通过使用get_categories类别名称() 代码是在这里:
<?php
$category_args = array(
'type' => 'your_post_type_slug',
'child_of' => 0,
'parent' => 0,
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => 0,
'hierarchical' => 1,
'exclude' => '',
'include' => '',
'number' => '',
'taxonomy' => 'your_taxonomy_slug',
'pad_counts' => false
);
$categories_array = get_categories($category_args);
echo '<div class="entry-categories"><span class="sr-only">'. esc_html__('Posted in ', 'positor') . '</span>';
foreach ($categories_array as $categories_val) {
echo '<span class="badge badge-primary"><a href="'.get_term_link(intval($categories_val->term_id), $categories_val->taxonomy).'"></span>'.$categories_val->name.'</a>';
}
?>