0

I've created two custom fields on the post edit screen using the ACF Pro plugin. If the fields are empty, I want to set the current user as both the field's value when the user clicks Publish button.

This is how I'm calling the function

add_action('transition_post_status', [$this, 'setOwnerAssignee'], 10, 3);

This is the setOwnerAssignee function

public function setOwnerAssignee($new_status, $old_status, $post)
{
    if ($new_status == 'publish' && $old_status != 'publish' && $post->post_type == 'post') {
        $current_user = strval(get_current_user_id());
        update_post_meta($post->ID, 'owner', $current_user, '');
        update_post_meta($post->ID, 'assigned', $current_user, '');
        // wp_die('die');
    }
}

I checked in PHPMyAdmin and the function properly sets the values if I use the wp_die in the end or if I remove the if condition. But it isn't working without that.

I'm fairly new to WordPress development so I might be doing something silly.

0

Seems like you need to change your action to publish_post.

publish_post only fires when a post is published. The callback function will only receive only one argument, the post id, with it you can do all your needed checks and update the meta as needed.

By the way, update post meta doesn't play well with ACF in the initial update. If meta field was empty it will sometimes not update it.

Acf has its own function to deal with meta updates update_field, better use it instead.

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.