Home Forums Front-end Issues Update taxonomy term field when a new post is published on the frontend


Update taxonomy term field when a new post is published on the frontend

  • I have a custom post type ‘venue’. Associated with ‘venue’ is a taxonomy ‘country’. In the ‘country’ taxonomy is a custom field called ‘total_live_venues’.

    On the frontend of the site I have an acf_form for creating new venues. This works fine. However, when attempting to update total_live_venues field (a count of all live venues) when a new venue is submitted on the frontend, nothing is saved to the field.

    Any ideas what I am doing wrong?

    Here is my function:

    function my_pre_save_post( $post_id ) {
        // check if this is to be a new post
        if( $post_id != 'new' ) {
            return $post_id;
        // the associated country (taxonomy term)
        $country_id = 'country_' . get_the_terms( $post_id, 'country')[0]->term_id;
        // the country's 'total_live_venues' count
        $total_live_venues = get_field('field_5c788ae1ec24a', $country_id);
        // increase the count by 1 when a new post is created on the frontend
        update_field('field_5c788ae1ec24a', $total_live_venues+1, $country_id);
        // return the new ID
        return $post_id;
    add_filter('acf/pre_save_post' , 'my_pre_save_post', 10, 1 );

    For those wondering why I’m not just using the default post count for the count, this is because there is a ‘discontinued’ field in venues which can be switched on from the backend and reduces the count by 1.

  • The reason that the value is not saved could be because your filter is never run.

    What are the setting for acf_form()?

    From looking at your code, you are depending on ACF to create the new post. ACF is probably creating the new post before your filter runs and this means that when your filter runs $post_id != "new".

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

You must be logged in to reply to this topic.