I 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
categoryterm 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_tagterm for the current post:$tags = get_the_tags(); if ( is_array( $tags ) && ! empty( $tags ) ) { echo esc_html( $tags[0]->name ); } -
Display the first
stateterm 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.