WordPress文章页面如何将分类名称转为带链接文本?
WordPress文章内显示带链接的分类(无多余连接词)
我想在WordPress文章页面的文本中显示对应文章分类的链接。目前已能显示父级与子级分类名称,但只是纯文本没有超链接;也试过用代码生成带链接的分类,但因为不确定文章的分类数量,总会出现多余的末尾“and”,一直达不到预期效果。之前尝试的代码如下:
$category = get_the_category(get_the_ID()); // get the current category object $child = get_category($category[0]->term_id); // get it's parent object $parent = get_category($child->parent); echo 'Providing help and guidance on ' . $child->name ; if ( $parent->name ) { echo ' and ' ; }; echo $parent->name;
$categories = get_the_category(); $cat = $categories[0]->cat_ID; echo get_category_parents( $cat, true, ' and ' );
解决方案1:适配任意数量分类的通用写法
以下代码会根据当前文章的分类数量自动调整连接词,避免出现多余的末尾“and”,同时生成带超链接的分类名称:
// 获取当前文章的所有分类 $categories = get_the_category(); $category_links = array(); // 遍历分类,生成带链接的HTML元素 foreach ($categories as $category) { $category_links[] = '<a href="' . get_category_link($category->term_id) . '">' . esc_html($category->name) . '</a>'; } // 根据分类数量拼接内容 if (!empty($category_links)) { $link_text = ''; $count = count($category_links); if ($count == 1) { $link_text = $category_links[0]; } elseif ($count == 2) { $link_text = implode(' and ', $category_links); } else { $last_link = array_pop($category_links); $link_text = implode(', ', $category_links) . ', and ' . $last_link; } echo 'Providing help and guidance on ' . $link_text; }
解决方案2:仅针对父级+子级分类的写法
如果只需要显示当前文章主分类的父级与子级分类链接,用以下代码更精准,不会出现多余连接词:
$category = get_the_category(get_the_ID()); if (!empty($category)) { $child_cat = $category[0]; $category_links = array(); // 添加子分类链接 $category_links[] = '<a href="' . get_category_link($child_cat->term_id) . '">' . esc_html($child_cat->name) . '</a>'; // 存在父分类时添加父分类链接 if ($child_cat->parent != 0) { $parent_cat = get_category($child_cat->parent); $category_links[] = '<a href="' . get_category_link($parent_cat->term_id) . '">' . esc_html($parent_cat->name) . '</a>'; } // 拼接并输出 echo 'Providing help and guidance on ' . implode(' and ', $category_links); }
内容的提问来源于stack exchange,提问作者Dom19811981
相关产品推荐
相关产品推荐

