I want to echo the term slug for each post on an archive page.
To get the term slug i'm using the following code:
$terms = get_the_terms( get_the_ID(), 'type_kennisbank' );
That returns me the data that I want:
array(1) { [0]=> object(WP_Term)#18648 (11) { ["term_id"]=> int(28) ["name"]=>
string(10) "Whitepaper" ["slug"]=> string(10) "whitepaper" ["term_group"]=>
int(0) ["term_taxonomy_id"]=> int(28) ["taxonomy"]=> string(15)
"type_kennisbank" ["description"]=> string(0) "" ["parent"]=> int(0)
["count"]=> int(3) ["filter"]=> string(3) "raw" ["term_order"]=> string(1) "0" } }
If I want to echo the slug I'm using:
echo $terms["slug"]
However it returns nothing. I already found a solution to echo the term slug but I'm wondering why my own echo code doesn't return the slug.
Anyone who can explain this?
I want to echo the term slug for each post on an archive page.
To get the term slug i'm using the following code:
$terms = get_the_terms( get_the_ID(), 'type_kennisbank' );
That returns me the data that I want:
array(1) { [0]=> object(WP_Term)#18648 (11) { ["term_id"]=> int(28) ["name"]=>
string(10) "Whitepaper" ["slug"]=> string(10) "whitepaper" ["term_group"]=>
int(0) ["term_taxonomy_id"]=> int(28) ["taxonomy"]=> string(15)
"type_kennisbank" ["description"]=> string(0) "" ["parent"]=> int(0)
["count"]=> int(3) ["filter"]=> string(3) "raw" ["term_order"]=> string(1) "0" } }
If I want to echo the slug I'm using:
echo $terms["slug"]
However it returns nothing. I already found a solution to echo the term slug but I'm wondering why my own echo code doesn't return the slug.
Anyone who can explain this?
Share Improve this question asked Dec 12, 2018 at 14:33 NielsPilonNielsPilon 3165 silver badges17 bronze badges 2 |1 Answer
Reset to default 2The get_the_terms
function returns array of WP_Term
objects.
So you need to use something like this to echo a single term slug:
echo $terms[0]->slug;
Also be aware of results of this function. As documentation says it returns:
Array of WP_Term objects on success, false if there are no terms or the post does not exist, WP_Error on failure.
So you need some checks before trying to echo terms. The following code may help you.
$terms = get_the_terms( get_the_ID(), 'type_kennisbank' );
if ( $terms && ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
echo $term->slug;
}
}
$terms
is an array and each item is an object. E.g. For the data in your question, you can doecho $terms[0]->slug;
to display the term slug. – Sally CJ Commented Dec 12, 2018 at 14:49get_the_terms()
could return aWP_Error
instance, or that the array could contain two or more items. All the best! – Sally CJ Commented Dec 13, 2018 at 2:03