i'd like to create a shortcode for wordpress to display the category name. Each post on the website is associated with only one category, so there is no need to display a list of categories but only one category name.
I have found here this code :
function categories_list_func( $atts ){
$categories = get_the_category();
if($categories) {
foreach($categories as $category) {
$output .= '<li>'.$category->cat_name.'</li>';
}
$second_output = trim($output);
}
$return_string = '<ul>' . $second_output . '</ul>';
return $return_string;
} // END Categories
add_shortcode( 'categories-list', 'categories_list_func' );
The code gives me a partial answer because the result shows a bullet before the category name. How to use the code without showing a bullet before the category name?
Correcting my question: what code is appropriate to show the category name?
The code in the example refers to a list, and this is appropriate for the case where a post is linked to more than one category. In my case there is only one category per post, so it is only necessary to display its name and not a list of names.
You would not need the <ul>
and <li>
tags, so those can be removed. Also, since you are no longer concatenating them into the string, the $second_output
variable can be updated with the $return_string
variable instead. Also, a couple minor tweaks in the snip below.
function categories_list_func( $atts ){
if($categories = get_the_category()) {
foreach($categories as $category) {
$output .= $category->cat_name;
}
$return_string = trim($output);
}
return $return_string;
} // END Categories
add_shortcode( 'categories-list', 'categories_list_func' );