简体   繁体   English

在WordPress中显示当前帖子的所有类别名称

[英]Display all category names for current post in wordpress

Using this Q&A as a guide, I've assigned multiple categories to my post (of a custom post-type). 以此问答为指导,我为我的帖子(自定义帖子类型)分配了多个类别。 Trying to display all the assigned categories using this code, which is placed in a separate file entirely, project-clipping.php . 尝试使用此代码显示所有分配的类别,该代码完全放在单独的文件project-clipping.php

$categories = get_the_category();
$cat_name   = $categories[0]->name;

foreach ( $categories as $i => $category ) {
  echo esc_html( $categories[0]->name );
  if ( $i < $count - 1 )
      echo $separator;
}

It works fine for the first category, but thereafter spits out a notice: Undefined variable: count in... . 对于第一个类别,它工作正常,但随后发出notice: Undefined variable: count in... This occurs thrice, twice, etc. depending on the number of categories assigned to the respective post. 这会发生三次,两次等,具体取决于分配给各个职位的类别数量。

I've tried solving this by placing it in the loop itself, rather than an external file. 我试图通过将其放置在循环本身而不是外部文件中来解决此问题。 Does not work. 不行。

I've also looked at this but it returns all the categories of the post-type, not the post. 我也看了这个 ,但它返回的类型后,不是职位的所有类别。

Thank you. 谢谢。

You didn't define count and separator variable it seems, try like this, change separator variable as per your need. 您似乎没有定义计数和分隔符变量,尝试这样,根据需要更改分隔符变量。

$categories = get_the_category( get_the_ID() ) // if you are using custom taxonomy replace with get_the_terms( get_the_ID(), 'your-taxonomy'); 
$separator = '|'; // define separator variable 
$count = count($categories); // define count
if ( ! empty( $categories ) ) { // check if not empty
    foreach ( $categories as $i=>$category ) {
      echo esc_html( $category->name );
      if ( $i < $count - 1 )
      echo $separator;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM