How do I get only the first term of a custom post type.
I can get all – no problem. This what I am using to grab all of them
<?php foreach ($terms as $term) {echo '<a href="'.get_term_link($term->slug, 'sitecat').'">'.$term->name.'</a>,';} ?> >> <a href="<?php the_permalink(); ?>"><?php the_title('', ''); ?></a></h2></span>
Would appreciate an answer using my code but any help is most welcomed
I’m not sure what you mean by ‘first’ taxonomy… but,
returns an array of taxonomy term objects, so
Would give you the first term in the array. And then:
(You may want to include some if statements, in case an empty array or error is returned (see
is_wp_error
)As of PHP 5.4, you can directly dereference an array, so to get the first term, you can simply do.
If you need a specific property (say the term name) of the first term, you can do the following
EDIT
Just a note, this does have its draw backs because you will get a
WP_Error
object if the taxonomy is invalid. Also, if the returned array is empty, you will also get an undefined array key warning, so use this with with care.how about directly access the key of object?
so you can access the object.
To summarize all the previous answers here is the helper gist I use. Does all the necessary checks and accepts same arguments as the get_the_terms() function.
Further note.
This function for simplicity that’s needed in most of my cases just returns the term object or false. You can still return WP_Error if up the flow you need check for it i.e.
Moreover you can sort the terms before returning the first i.e. so you get first term object by term_id, slug, name, menu order and so on.
It worked for me. It brings only the first category as text, no anchor.