marcelo2605
marcelo2605

Reputation: 2794

Can't remove an object from a multi dimensional array

The function wp_get_post_terms returns an object

$terms = wp_get_post_terms( get_the_ID(), 'category', $args );

I need to remove one of these objects based on it's values:

$current_id = get_queried_object_id();
 foreach( $terms as $key => $value ){
   if( in_array($current_id, $value[$key]) ){
     unset($terms[$key]);
   }
}

But I'm stuck in this error:

Uncaught Error: Cannot use object of type WP_Term as array

Upvotes: 0

Views: 109

Answers (2)

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

You may want to save valid terms into a second array:

$terms = wp_get_post_terms( get_the_ID(), 'category', $args );
$validTerms = [];
$current_id = get_queried_object_id();
foreach( $terms as $key => $value ){
   if( $value->term_id != $current_id) {
       $validTerms[$key] = $value;
   }
}

Edit

The error is stemming from the if statement, as Julien Lachal has explained.

As such, here is the same answer as above unsetting the offending term:

$terms = wp_get_post_terms( get_the_ID(), 'category', $args );
$current_id = get_queried_object_id();
foreach( $terms as $key => $value ){
   if( $value->term_id == $current_id) {
       unset($terms[$key]);
       break; //Found our guilty term, no need to continue the `foreach`.
   }
}

Upvotes: 1

Julien Lachal
Julien Lachal

Reputation: 1141

I think your error lies here :

if( in_array($current_id, $value[$key]) ){

because $value is a WP_Term, but you're trying to access it using the $key (which is linked to the index of $terms not $value.

Upvotes: 1

Related Questions