Support

Account

Home Forums Front-end Issues Run a function when a post is saved via a front-end form

Solved

Run a function when a post is saved via a front-end form

  • I have created a function that runs each time a post (of a custom post type) is saved. It takes some data from some ACF fields, and does some other stuff with it.

    function doublee_apply_style_terms() {
     // do some stuff
    }
    add_action( 'publish_post', 'doublee_apply_style_terms' );
    add_action( 'save_post', 'doublee_apply_style_terms' );
    add_action( 'edit_post', 'doublee_apply_style_terms' );
    add_action( 'acf/save_post', 'doublee_apply_style_terms' );
    

    The function itself seems to be fine (hence omitting the details here) because it works as intended when the post is saved from the admin. However, it doesn’t take effect when the post is updated via an ACF front-end form.

    As you can see I tried acf/save_post but no luck. Is there a way to run a separate function on post save via front-end form?

  • acf/save_post runs on bot sides, any time that acf fields are present.

    You should not be using any of these

    
    add_action( 'publish_post', 'doublee_apply_style_terms' );
    add_action( 'save_post', 'doublee_apply_style_terms' );
    add_action( 'edit_post', 'doublee_apply_style_terms' );
    

    The reason why is that doing so means that your action/filter will run multiple times when there are ACF fields. You should only be using acf/save_post.
    See the documentation here https://www.advancedcustomfields.com/resources/acf-save_post/
    ACF passes one value, the Post ID. If the problem is that the ACF fields are not returning anything that is due to the priority not being high enough and you need to set that to 20 to run after acf has saved the values. Again, see that doc.

  • Thank you so much for your quick reply and clear advice John, it is much appreciated.

    The priority was the key here. I tried acf/save_post at priority 20 (and higher) as you suggested, but it still didn’t work. But the doc you linked to mentioned using save_post in some circumstances so I tried using just save_post at priority 30 and that works perfectly.

    Thank you again!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.