0
votes

I am using Meta-Box plugin for custom fields and I have custom post types as well. When an User enters something into a custom field and then saves the custom post type, I calculate something and depending on the calculated value I then write something into another custom field. As this doesn't work properly, I broke it down to a much simpler function to test the behavior and find the issue. This is what the simpler function does:

-the custom post type shows 2 drop downs (custom fields) -the User selects something in the first drop down and then saves/updates the post -the function then selects the same selected value/item from the first drop down in the second drop down

I am using the save_post hook, which then correctly takes the selected value and sets the same value for the second custom field with the update_post_meta() function. The value is correctly written into the DB after saving and updating the post, but the custom field in the admin interface doesn't show the right value. This is the code:

add_action( 'save_post', 'update_second_custom_field' );

function update_second_custom_field( $post_id ) {
    $firstCustomFieldValue=get_post_meta($post_id, 'first_custom_field', true);
    update_post_meta($post_id, 'second_custom_field', $firstCustomFieldValue);
    $test = get_post_meta($post_id, 'second_custom_field', true);
    _log($test);
}

The second custom field doesn't seem to get updated in the admin view. Doesn't matter what I do, reopening the post, updating again. It will always display the standard value, even though it seems the db has the correct value.

What am I missing here?

EDIT Okay I have to correct my initial post. It seems the value is not written into the DB. I just don't get why. Why does get_post_meta show the correct value but the DB holds the old value. Doesn't get_post_meta get the value from the DB? I am totally confused ^^.

1

1 Answers

1
votes

Okay, I found the issue myself.

I thought that save_post is called when everything has been already written into the DB, but it seems it is not. In my case, I set the second custom field value by code, but the post was first saved after my function. So the value that I set was overwritten with the selection that was done in the admin area, which was the standard value.

My solution was to use wp_insert_post instead of save_post.