Search code examples
wordpresssaveadvanced-custom-fieldspublish

Save ACF field when publish or update post


When I publish or update a post, I want to save the slug of the post in an ACF field nammed "plan_slug". The code I wrote is:

add_action('future_to_publish', 'actions_published_post');
add_action('new_to_publish', 'actions_published_post');
add_action('draft_to_publish' ,'actions_published_post');
add_action('auto-draft_to_publish' ,'actions_published_post');

function actions_published_post($post) {
  update_field('plan_slug', $post->post_name);
}

Nothing runs good! The field in post back-end is not fullfilled...

Can you, please, tell me what is wrong in my code. Thank you in advance.


Solution

  • this should work

    add_action( 'save_post', 'save_custom_field', 10, 2);
    function save_custom_field( $post_id, $post ) {
        update_post_meta( $post_id, 'plan_slug', $post->post_name );
    }