wp_set_object_terms() is not replacing term, but creating a new one

In both the cases issue is not the other things, but the main value what you are sending to the second parameter, in your case $flightCategory:

$flightCategory = array( 25 );
var_dump( $flightCategory );
wp_set_object_terms( $post_id, $flightCategory, 'flight_categories' );

But on the later version somehow, or literally you are actually passing something like below:

$flightCategory = array( '25' );
var_dump( $flightCategory );
wp_set_object_terms( $post_id, $flightCategory, 'flight_categories' );

Did you note the SINGLE QUOTE around 25? That’s actually causing the issue. Because on the first code dump you will see:

array(1) { [0]=> int(25) }

And on second one:

array(1) { [0]=> string(2) "25" }

You are actually passing a string, and the function understands that, Okay, I got the Term name, so be it. But with an integer you are actually saying, Hey function, now got the Term ID, add/update the ID only.

SOLUTION

To solve the problem you have to do a simple thing:

$flightCategory = (int)$flightCat; //make it integer whatever you get

or,

$flightCategory = array( (int)$flightCat );  //make the array value integer whatever you get

Learn more about PHP Type casting.

Leave a Comment