【问题标题】:Wordpress custom post type how to display taxonomy description in single postWordpress自定义帖子类型如何在单个帖子中显示分类描述
【发布时间】:2021-05-17 17:29:39
【问题描述】:

我正在尝试在单个帖子的前端显示自定义分类项目描述。

以下情况:

  1. 为“Weine”创建了 CPT
  2. 添加了分类法“winzer”
  3. 在我的 functions.php 中添加了以下代码,以使用简码在单个帖子中显示“winzer”分类项目及其描述:
function wpb_catlist_desc() { 
$string = '<div>';
$catlist = get_terms( 'winzer' );
if ( ! empty( $catlist ) ) {
  foreach ( $catlist as $key => $item ) {
    $string .= '<div>'. $item->name . '<br />';
    $string .= '<em>'. $item->description . '</em></div>';
  }
}
$string .= '</div>';
 
return $string; 
}
add_shortcode('wpb_categories', 'wpb_catlist_desc');

代码运行良好,但它显示了我在“Winzer”分类中创建的所有项目。

我只想显示与单个帖子相关的项目。

关于如何更改代码以完成此操作的任何想法?

干杯!!!!

【问题讨论】:

  • 尝试使用 get_the_terms() 代替。

标签: php wordpress custom-post-type custom-wordpress-pages


【解决方案1】:

您可以使用get_the_terms() 而不是get_terms()。所以你可以这样做:

add_shortcode('wpb_categories', 'wpb_catlist_desc');

$the_id_of_current_post = get_the_ID(); // get the id of the current post

// pass the id to your function
function wpb_catlist_desc($the_id_of_current_post) 
{ 
  $string = '<div>';
  
  $$catlist = get_the_terms( $the_id_of_current_post, 'winzer' );

  if ( ! empty( $catlist ) ) {
    foreach ( $catlist as $cat ) {
      $string .= '<div>'. $cat->name . '<br />';
      $string .= '<em>'. $cat->description . '</em></div>';
    }
  }

  $string .= '</div>';
  
  return $string; 
}

或者另一种方法是这样的:

add_shortcode('wpb_categories', 'wpb_catlist_desc');

function wpb_catlist_desc() 
{ 
  global $post;

  $the_id_of_current_post = $post->ID; // get the id of the current post

  $string = '<div>';
  
  $$catlist = get_the_terms( $the_id_of_current_post, 'winzer' );

  if ( ! empty( $catlist ) ) {
    foreach ( $catlist as $cat ) {
      $string .= '<div>'. $cat->name . '<br />';
      $string .= '<em>'. $cat->description . '</em></div>';
    }
  }

  $string .= '</div>';
  
  return $string; 
}

让我知道你是否能够让它工作!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多