My existing data in the termmeta table:
| meta_id | term_id | meta_key | meta_value |
|---|---|---|---|
| 27374 | 546 | 1C_id | 9095b4cf-969d-11e9-a601-5cf3706390c8 |
| 27918 | 546 | tax_position | 1 |
My code:
$found_id = $wpdb->get_var("SELECT term_id FROM `{$wpdb->prefix}termmeta` WHERE meta_value='{$group['1C_id']}'");
if(!empty($found_id)) $wpdb->update($wpdb->prefix.'termmeta', array('meta_key' => '1C_id', 'meta_value' => $group['1C_id']), array('term_id'=>$found_id));
This deletes the tax_position meta and duplicates the 1C_id meta row, can’t figure out why. No other piece of my code deals with this meta field.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Your UPDATE command would look like so after all variables are substituted — and in this example, the table prefix is wp_ (the default one), $group['1C_id'] is 9095b4cf-969d-11e9-a601-5cf3706390c8, and $found_id (the term ID) is 123.
UPDATE `wp_termmeta`
SET `meta_key` = '1C_id', `meta_value` = '9095b4cf-969d-11e9-a601-5cf3706390c8'
WHERE `term_id` = 123
So that means, all existing meta where the term ID is 123 and regardless what the meta key is, will be changed:
-
First, the meta key is set to
1C_id, so thetax_positionmeta was renamed to1C_id. -
Secondly, the meta value is set to
9095b4cf-969d-11e9-a601-5cf3706390c8, which became thetax_position‘s new value.
So that explains this: “This deletes the tax_position meta and duplicates the 1C_id meta row“.
I.e. The tax_position meta was not deleted, but only its key and value that were changed, and that they’re set to the same ones for the existing 1C_id meta.
Therefore, $wpdb->update() did not actually delete or add any metadata. It’s your query which isn’t done correctly.
So maybe you’re trying to do something like this?
Note that I used $wpdb->prepare() to prepare the query for safe execution, and you should do the same.
// Select meta IDs by meta value.
$meta_ids = $wpdb->get_col( $wpdb->prepare( "
SELECT meta_id FROM $wpdb->termmeta
WHERE meta_value = %s
", $group['1C_id'] ) );
// Then update all the above meta by the meta ID.
if ( ! empty( $meta_ids ) ) {
$wpdb->query( $wpdb->prepare( "
UPDATE $wpdb->termmeta
SET meta_key = '1C_id', meta_value = %s
WHERE meta_id IN (" . implode( ',', $meta_ids ) . ")
", $group['1C_id'] ) );
/* Or you can use update_metadata_by_mid():
foreach ( $meta_ids as $meta_id ) {
update_metadata_by_mid( 'term', $meta_id, $group['1C_id'], '1C_id' );
}
*/
}
But then, why are you UPDATE-ing the meta value with the same value ($group['1C_id']) used when SELECT-ing the meta? Was that a typo? (Maybe you just wanted to update the meta key..?)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0