• I’ve been banging my head against the wall for quite some time now to no avail. According to the comments in post.php (and online), the save_post action is supposed to fire after the post and post meta have been saved to the database.

    When I attempt to retrieve the post meta from this action, I am only getting the post meta before the save. I’ve created a clean install with no plugins and am able to replicate the results. Please find my code below.

    function update_custom_field( $post_id, $post, $update ) {
    	$myfile = fopen( 'test.txt', 'w' );
    	fwrite( $myfile, print_r( get_post_meta( $post_id ), true ) );
    	fclose( $myfile );
    }
    add_action( 'save_post', 'update_custom_field', 20, 3 );

    In order to see the new post meta in the file, I have to save the post twice.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Thread Starter lkhulusi

    (@lkhulusi)

    Also, to add more context, I’m creating the a custom field custom_field_1 in the admin and entering a value from the admin. Using the twentytwenty theme.

    Moderator bcworkz

    (@bcworkz)

    You have a race condition where your code executes before SQL has time to update the metadata. For post post_type meta data, you can use the “updated_postmeta” action to do something when metadata is updated or added.

    Thread Starter lkhulusi

    (@lkhulusi)

    Thanks for the response.

    I initially thought it was a RACE condition as well, but when I delay the code within the function for 10 seconds, I still get the same results.

    I’ve attempted updated_postmeta by only switching the action name in the hook. It does not seem to be firing at all. I added die(); in the first line of code and I do not get any errors, and the output of the file does not change even after updating multiple times. As soon as I change the action back to save_post whatever code I have is executed.

    Are you able to try my code (or something similar) and get the expected results?

    Moderator bcworkz

    (@bcworkz)

    I know from past experience that trying to get saved post meta from “save_post” does not work. I blamed on a race condition. Perhaps that’s wrong, but the fact remains it does not work. So there’s little point in testing your code as-is. “updated_postmeta” passes parameters differently than “save_post” so you need to rearrange your callback parameters.

    Also, it is only for “post” post type. You need a different action for other types. The code that fires off the action starts here FYI. For starters, you have to collect 4 parameters in order to get the saved value.

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘save_post returning old post meta’ is closed to new replies.