3

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 = 'test@test.com';
    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.

Ruvee
  • 8,611
  • 4
  • 18
  • 44
mickdeez
  • 507
  • 3
  • 7
  • 16
  • Try to check if your if statement is correct. I would suggest using != btw. Other option is to insert a different email adress by the if statement and update field with this email adres. This way you can see if the problem is not with the if statement, – Webdever Sep 02 '21 at 21:47

2 Answers2

3

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 = 'coachtest@test.com';

    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!

Ruvee
  • 8,611
  • 4
  • 18
  • 44
1

I find sometimes using acf/save_post, upping the priority makes sure everything else has run before running the action function.

This might come into play when passing an $post_id in the get_field() function, I tend not to pass the $post_id when using acf/save_post to make sure the current latest field data is used. But this theory might not be the case. See comments in code below...

<?php

// save post action with priority 20 (default 10)
add_action('acf/save_post', 'set_coach_email', 20);

/**
 * @param $post_id int|string
 */
function set_coach_email($post_id) {

    // get our current post object
    $post = get_post($post_id);

    // if post is object
    if(is_object($post)) {

        // check we are on the team custom type and post status is either publish or draft
        if($post->post_type === 'team' && ($post->post_status === 'publish' || $post->post_status === 'draft')) {

            // get coach email field
            $coach_email = get_field('coach_email');
            
            // if coach email field returns false
            if(!$coach_email) {

                // coach email default
                $email = 'coachtest@test.com';

                // update coach email field
                update_field('coach_email', $email, $post->ID);

            }

        }

    }

    // finally return
    return;

}
joshmoto
  • 4,472
  • 1
  • 26
  • 45