• 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.

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    There’s nothing wrong with your code. It works fine on my site. TBH, I “de-OOPed” it, making it into a procedural function, but changed nothing else.

    Could it be your class wasn’t instantiated? Or not instantiated early enough? Is your add_action() call within the class’ constructor? Otherwise $this could be out of scope.

Viewing 1 replies (of 1 total)

The topic ‘How to update custom fields when post is published?’ is closed to new replies.