我们总是会给自己的自定义文章类型,加上自己的自定义分类,怎么在文章里输出这个分类地址呢?
默认文章页面
<?php the_category();?>
自定义文章页面
<?php
$post = get_post($post);
$post_type = get_post_type_object(get_post_type());
$post_type_name = $post_type->labels->singular_name;
$slug = $post_type->rewrite;
if ($slug['slug'] != '') {
echo '<a href="' . home_url() . '/' . $slug['slug'] . '/">' . $post_type_name . '</a> '; //自定义文本类型地址
}
$taxonomy_names = get_the_taxonomies(); //所有分类
// print_r($taxonomy_names);
foreach ($taxonomy_names as $taxonomy => $vvv) {
if ($taxonomy != 'post_tag') {
if ($taxonomy != 'category') {
$taxonomy_name = get_taxonomy($taxonomy)->labels->name;
echo '<a href="' . home_url() . '/' . $slug['slug'] . '/' . $taxonomy . '/">' . $taxonomy_name . '</a> '; // 某某分类地址
}
$terms = get_object_term_cache($post->ID, $taxonomy);
foreach ($terms as $term) {
echo '<a href="' . esc_url(get_term_link($term->term_id, $taxonomy)) . '">' . $term->name . '</a>'; //分类地址
}
}
}
?>
精简一下
<?php
$post = get_post($post);
$taxonomy_names = get_the_taxonomies(); //所有自定义分类
foreach ($taxonomy_names as $taxonomy => $vvv) {
if ($taxonomy != 'post_tag') {
$terms = get_object_term_cache($post->ID, $taxonomy); //自定义分类下面的所有自建分类
$term = $terms[0]; //第一个分类
// print_r($term);
echo '<a href="' . esc_url(get_term_link($term->term_id, $taxonomy)) . '">' . $term->name . '</a>'; //分类地址
}
}
?>
你们会喜欢这个代码的,通用
<?php
$post = get_post($post);
foreach (get_object_taxonomies($post) as $taxonomy) {
if ($taxonomy != 'post_tag') {
echo get_the_term_list($post->ID, $taxonomy, '');
}
}
?>