Shortcode to show current post category with link

I want to display the current post category with link using shortcode [post_category]. The current code I got below show

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' );

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745363102a4624451.html

相关推荐

  • Shortcode to show current post category with link

    I want to display the current post category with link using shortcode [post_category]. The current code I got below show

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信