Search code examples
wordpresswordpress-themingadvanced-custom-fieldscustom-post-typecustom-wordpress-pages

Wordpress how to update ACF field in a custom post type after the post has been saved


I'm trying to set the value of a field in a custom post type right after that post has been created. Here is my code:

add_action('acf/save_post', 'set_coach_email');
function set_coach_email( $post_id ){
    $posttype = get_post_type($post_id);
    if ('team' !== $posttype){
        return;
    }
    $email = '[email protected]';
    update_field('coach_email', $email, $post_id);
}

I used ACF fields to create this custom post type, but I can't seem to get it to work.


Solution

  • I'd check the opposite conditional check. Also i'd first check if the field is empty or not, then i'd only run the update if the field is empty.

    add_action('acf/save_post', 'set_coach_email');
    
    function set_coach_email($post_id)
    {
      $posttype = get_post_type($post_id);
    
      $email_field = get_field('coach_email', $post_id);
    
      if ('team' == $posttype && empty($email_field)) {
    
        $email = '[email protected]';
    
        update_field('coach_email', $email, $post_id);
    
      }
    }
    

    Just tested on my own custom post type and it worked fine. Let me know if you could get it to work too!