php - 使用 foreach 循环显示帖子类别一次
问题描述
我正在尝试根据类别显示帖子。我创建了短代码来显示帖子 [knowledge_sharing cat="docs" posts_per_page="5"]
代码:-
function cat_post($atts){
// attributes for shortcode
if (isset($atts['cat'])) {$cat = $atts['cat'];} else {return;}
if (isset($atts['posts_per_page'])) {$posts_per_page = $atts['posts_per_page'];} else {$posts_per_page = -1;}
// get the category posts
$category = get_category_by_slug($cat);
if (!is_object($category)) {return;}
$args = array(
'cat' => $category->term_id,
'posts_per_page' => $posts_per_page,
'post_type' => 'knowledgeSharingDocs',
'order' => 'DESC'
);
$posts = get_posts($args);
// create the list output
if (count($posts) > 0) {
$cat_title = get_the_category($posts->ID);
foreach($cat_title as $cd){
$output .='<div class="category-name do-title dot-symbol ">' .$cd->cat_name. '</div>';
}
$output .= '<div class="category-list">';
foreach ($posts as $post) {
$link = get_permalink($post->ID);
$title = $post->post_title;
$output .='<div class="category-boxs">';
$output .='<div class="category-titles"><a href="'.$link.'">' .$title. '</a></div>';
$output .='<div class="category-decs">' .$post->post_content. '</div>';
$output .='</div>';
}
$output .= '</div>';
return $output;
}
}
不知何故,此代码仅显示帖子标题和内容,而不显示类别名称。
我希望输出是这样的:- 类别名称 post 1 post2 post 3
类别名称仅一次。提前致谢。
解决方案
你试过这个:
$categories = get_the_category( $post->ID );
var_dump( $categories );
您可以使用 https://developer.wordpress.org/reference/functions/get_the_category/
推荐阅读
- java - 并行流() java 1.8 与 11
- azure - azure datalake gen2 databricks ACL 权限
- c++ - 如何在没有taskkill的情况下重新启动资源管理器
- flutter - Flutter:无法将 ListView 添加到示例应用程序
- swiftui - SwiftUI 列表未显示任何项目
- visual-studio - 'SMTP 服务器需要安全连接或客户端未通过身份验证。服务器响应为:5.7.0 Authentication Required
- javascript - 如何在html5和js中下载部分视频
- javascript - 替代“onScroll”来隐藏导航栏?
- asp.net - 如何让 IIS 尊重相对路径?
- mongodb - MongoDB聚合检查数组是否包含值