博客 / WordPress 教程

WordPress文章页打印分类及自定义分类

打印文章默认分类:

<?php
  $categories = get_the_category(); 
  if (!empty($categories)) :
    foreach ($categories as $category) {
        echo '<a href="' .esc_url(get_category_link($category->term_id)). '?post_type=post" class="op-07 ls-1">' . $category->name . '</a>';
      }
  else:
  	echo '<span class="op-07 ls-1">默认分类</span>';
	endif;
?>

打印自定义分类(为自定义post-type打印)

<?php 
	// 获取并输出自定义分类 'resource_category'
  $terms = get_the_terms(get_the_ID(), 'resource-category');
  if ($terms && !is_wp_error($terms)) :
    foreach ($terms as $term) {
  	  $term_link = get_term_link($term); // 获取分类链接
  	  if (!is_wp_error($term_link)) {
        echo '<a href="' . esc_url($term_link) . '" class="pe-3">' . esc_html($term->name) . '</a>';
      }else{
      	echo esc_html($term->name);
      }
    }
  endif; 
?>

评论留言

您的邮箱地址不会被公开。 必填项已用 * 标注