echo $category[0]-> cat_name; shows only one category name
-
18-04-2021 - |
سؤال
I have this code:
<div class="row">
<div class="col-lg-12 post_meta">
<ul>
<li>
<p class="meta-txt">Category</p>
<p class="meta-des"><?php $category = get_the_category(); echo $category[0]-> cat_name; ?></p></li>
<li>
<p class="meta-txt">Published</p>
<p class="meta-des"><?php the_time('F j, Y'); ?> </p></li>
<li>
<p class="meta-txt"><?php echo get_comments_number(); ?> Comments</p>
<p class="meta-des"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></p></li>
</ul>
</div>
</div>
It shows only one category as you can see on that link:
http://www.migrate2.deniz-tasarim.site/2020/01/10/yazi-9/
Also I want to show tags as list and link to categories and tags.How can I do it?
المحلول
In your code:
$category = get_the_category(); echo $category[0]-> cat_name;
get_the_category() returns and array of WP_Term objects. You are getting the first one from the array, and echoing only that one category name.
I'd recommend using get_the_category_list() instead.
$categories_list = get_the_category_list( esc_html__( ', ', 'html5blank' ) );
if ( $categories_list ) {
echo '<li><p class="meta-txt">', esc_html__( 'Category', 'html5blank' ), '</p><p class="meta-des">', $categories_list, '</p></li>';
}
There is also the method get_the_tag_list()
which you can use in a similar fashion to get the tags as you mentioned wanting to do that.
Altogether you would end up with something similar to this:
<div class="row">
<div class="col-lg-12 post_meta">
<ul>
<?php
$categories_list = get_the_category_list( esc_html__( ', ', 'html5blank' ) );
if ( $categories_list ) {
echo '<li><p class="meta-txt">', esc_html__( 'Category', 'html5blank' ), '</p><p class="meta-des">', $categories_list, '</p></li>';
}
$tags_list = get_the_tag_list( '', esc_html_x( ', ', 'list item separator', 'html5blank' ) );
if ( $tags_list ) {
echo '<li><p class="meta-txt">', esc_html__( 'Tag', 'html5blank' ), '</p><p class="meta-des">', $tags_list, '</p></li>';
}
?>
<li>
<p class="meta-txt">Published</p>
<p class="meta-des"><?php the_time('F j, Y'); ?> </p></li>
<li>
<p class="meta-txt"><?php echo get_comments_number(); ?> Comments</p>
<p class="meta-des"><?php if (comments_open( get_the_ID() ) ) comments_popup_link( __( 'Leave your thoughts', 'html5blank' ), __( '1 Comment', 'html5blank' ), __( '% Comments', 'html5blank' )); ?></p></li>
</ul>
</div>
</div>
لا تنتمي إلى wordpress.stackexchange