I am trying to update a custom field (order) inside a POST when it is saved. Everything is working smoothly according to my logs, even the function returns true, but the value does not change as it should.
Here is my code:
function update_on_save($post_id) {
error_log("fonction post_id :".$post_id);
// Enregistrement automatique = on sort
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if ($post_id && get_post_type($post_id) == 'post') {
if(in_category('Orquera Listings',$post_id)) {
$status = get_post_meta($post_id,'status', true);
error_log("status :".$status);
switch ($status) {
case 'Pending':
$order = 1;
break;
case 'For Sale':
$order = 2;
break;
case 'Sold':
$order = 3;
break;
default:
$order = 4;
}
error_log("order : ".$order);
$result = update_post_meta($post_id, 'order', $order);
error_log('result :'.$result);
}
}
}
add_action('save_post', 'update_on_save', 90,1);
My logs gives me:
Which is what I want, here, order should be set to 3, but my data is not being updated.
What am I doing wrong?
I have tried a lot of things, even tried using wp_after_insert_post, but so far my 'order' field has not moved an inch.
Adding parameters: $result = update_post_meta($post_id, 'order', $order,$old_order);
Changing priority...
Edit :
I tried this:
$wpdb->update($wpdb->prefix.'postmeta', array('meta_value' => $order), array('post_id' => $post_id,'meta_key' => 'order'));
$order_db = get_post_meta($post_id,'order', true);
error_log('order_db :'.$order_db);
It shows 3 in order. I feel like the value is saved again when I update the form. The "order" field can be edited, but I want to force the value.
To be clear: I am saving the post and I put 30 inside the order field to test it out. But this value will be overriden by my snippet thanks to save_post. I feel like it's updated, but the value I inputed in the field in the BO override it and save it again after.
I was able to fix the issue, this is how I did it:
add_action('acf/save_post', 'my_acf_save_post', 5);
$status = $_POST['acf']['field_64a6b0ced7f03']; // to get a value
$_POST['acf']['field_66193c3aec000'] = $order; // to put a value inside the field