最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Shortcode to show current post category with link

programmeradmin0浏览0评论

I want to display the current post category with link using shortcode [post_category]. The current code I got below shows the current category as text. I want it to be a link to the category. Thanks.

function category_name_shortcode(){
    global $post;
    $post_id = $post->ID;
    $catName = "";
    foreach((get_the_category($post_id)) as $category){
        $catName .= $category->name . " ,";
    }
    return $catName;
}
add_shortcode('post_category','category_name_shortcode');

I want to display the current post category with link using shortcode [post_category]. The current code I got below shows the current category as text. I want it to be a link to the category. Thanks.

function category_name_shortcode(){
    global $post;
    $post_id = $post->ID;
    $catName = "";
    foreach((get_the_category($post_id)) as $category){
        $catName .= $category->name . " ,";
    }
    return $catName;
}
add_shortcode('post_category','category_name_shortcode');
Share Improve this question edited Jun 28, 2019 at 9:56 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Jun 28, 2019 at 9:44 Joe TitusJoe Titus 391 silver badge6 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

One way of doing it would be to modify your current code and add the links in there:

function category_name_shortcode() {
    global $post;
    $post_id = $post->ID;
    $catName = "";
    foreach((get_the_category($post_id)) as $category){
        $catName .= '<a href="' . get_term_link($category) . '">' . $category->name . '</a>, ';
    }
    return $catName;
}
add_shortcode( 'post_category', 'category_name_shortcode' );

But there’s an easier way, because WP already has a way to obtain the list of categories with links (get_the_category_list):

function category_name_shortcode() {
    return get_the_category_list( ', ' );
}
add_shortcode( 'post_category', 'category_name_shortcode' );
发布评论

评论列表(0)

  1. 暂无评论