I'm working on a query to show related items op a CPT by the term assigned to the current post.

I already have the code to complete the query but don't get it why my initial code returns a NULL

To get the term assigned to the post I'm using this code

$terms = get_the_terms( $post->ID, 'taxonomy_name' );

If I do a var_dump of the $terms I get this in return

array(1) { [0]=> object(WP_Term)#1423 (10) { ["term_id"]=> int(5) ["name"]=> 
string(6) "Bilbao" ["slug"]=> string(6) "bilbao" ["term_group"]=> int(0) 
["term_taxonomy_id"]=> int(5) ["taxonomy"]=> string(15) "taxonomy_name" 
["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(2) 
["filter"]=> string(3) "raw" } }

To use the slug in my wp_query I thought I could use $terms->slug. However this returns a NULL.

After doing a search I found that this adjustment solved the issue foreach ( $terms as $term ) and then $term->slug

I only don't understand why I should use the for each part and can't use the string of the $terms in my query. Can someone explain me that?


$terms is an array of terms, so PHP doesn't know what you mean when you say $terms->slug.

With foreach, you're iterating through this array. If you only care about the first element, you can simply use $slug = $terms[0]->slug;. This will get you in trouble when there are no terms, though, so you will want to make sure you only operate that if there are terms, with something like

$queryparams = array("post_type" => "mycpt");
if(count($terms)) {
    $slug = $terms[0]->slug;
    // modifiy your queryparams here
    $queryparams["tax_query"] = ...

In other words because you have an array of Objects(in your case you only have 1 object). And you want to access that objects slug, and not the slug of the array.

  • Yeah, I got confused because it only returns one object, thanks – NielsPilon Jan 17 '18 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.