首页 > 解决方案 > 使用 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

类别名称仅一次。提前致谢。

标签: phpwordpressshortcode

解决方案


你试过这个:

  $categories = get_the_category( $post->ID );
  var_dump( $categories ); 

您可以使用 https://developer.wordpress.org/reference/functions/get_the_category/


推荐阅读