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
1 Answer
Reset to default 1One 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
评论列表(0条)