Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this questionI need to display it on each post.
Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this questionI need to display it on each post.
Share Improve this question edited Feb 26, 2022 at 19:22 asked Feb 24, 2022 at 23:29 user212573user2125731 Answer
Reset to default 0I need to display it on each post and only the first state if it has multiple states
I noticed there are $categories = get_the_category();
and echo esc_html($categories[0]->name);
in your code, which display the first category for the current post, but then note that get_the_category()
only returns results for the default/core category
taxonomy.
For custom taxonomies, you should use get_the_terms()
instead of get_the_category()
. And just so you know, for tags, i.e. the default post_tag
taxonomy, you can use get_the_tags()
.
Working Examples
Display the first
category
term for the current post:(you already have this in your code, but I included this just for completeness)
$categories = get_the_category(); if ( ! empty( $categories ) ) { echo esc_html( $categories[0]->name ); }
Display the first
post_tag
term for the current post:$tags = get_the_tags(); if ( is_array( $tags ) && ! empty( $tags ) ) { echo esc_html( $tags[0]->name ); }
Display the first
state
term for the current post:$states = get_the_terms( get_the_ID(), 'state' ); if ( is_array( $states ) && ! empty( $states ) ) { echo esc_html( $states[0]->name ); }
So as you could see, in the last example, I used get_the_terms()
because state
is a custom taxonomy.