4

From a custom Submenu Page if I use a hard code like:

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

And refresh the page, it simply assigns the desired Custom Taxonomy Terms to the CPT. But if I proceed with the following code, where I'm taking the values from a <form>, it's not working as previous.

if( $flightID !== NULL && $flightCat !== '-1' && !empty( $flightCat ) ) {
    $flightCount = count( $flightID );
    foreach ( $flightID as $post_id ) {
        $flightCategory = array( $flightCat ); //inactive = 25, active = 26
        wp_set_object_terms( $post_id, $flightCategory, 'flight_categories' );
    }
    $success = sprintf( __('<strong>SUCCESS:</strong> %d Flight information has been affected', 'textdomain'), $flightCount);
} else {
    $error = __('<strong>ERROR:</strong> You can\'t pass any empty field', 'textdomain');
}

What this code block is doing, it simply adds new Term named '25' with slug '25'. I tried to not passing an array like below:

$flightCategory = $flightCat;

But the result is same. What am I doing wrong?

10

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.

| improve this answer | |
  • 2
    some times it is just unbelievable how stupidly an API can be designed :( – Mark Kaplun Mar 27 '17 at 5:33
  • 2
    @MarkKaplun I don't feel it is stupid at all. Because of how it is designed we have the freedom to name a category '25'. Type casting is actually very important in many cases. – Justin Waulters Feb 13 '19 at 2:50

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.