Support

Account

Home Forums Front-end Issues Updating order issue Reply To: Updating order issue

  • Hi Kyllian,

    You’ve actually diagnosed the problem perfectly – this is indeed a hook timing issue where the post meta is being saved before your calculated field updates. The acf/save_post hook fires at different priorities, and your calculation is likely running too late in the sequence.

    Here’s a cleaner solution that should fix the two-save requirement:

    1. Replace Your PHP Snippet with Efficient ACF Logic

    Instead of using a separate shortcode, handle the calculation directly within your ACF setup. Add this to your functions.php:

    php
    function calculate_completion_percentage( $post_id ) {
    // Define all your file fields
    $file_fields = array(‘cni’, ‘rib’, ‘justif’, ‘lettre’, ‘der’, ‘situation’);
    $filled_count = 0;

    // Count how many fields have files
    foreach( $file_fields as $field ) {
    if( get_field($field, $post_id) ) {
    $filled_count++;
    }
    }

    // Calculate percentage
    $percentages = array(0, 17, 33, 50, 67, 83, 100);
    $completion = isset($percentages[$filled_count]) ? $percentages[$filled_count] : 0;

    // Update the ACF field directly
    update_field(‘sum’, $completion, $post_id);

    return $completion;
    }
    2. Hook with Correct Priority

    Now hook this function to run at the right time during save:

    php
    // Run after ACF has saved all fields but before post is fully committed
    add_action(‘acf/save_post’, ‘update_completion_on_save’, 15);
    function update_completion_on_save( $post_id ) {
    // Only run for main posts (not revisions)
    if( wp_is_post_revision($post_id) ) {
    return;
    }

    calculate_completion_percentage( $post_id );
    }
    3. Update Your Query Code

    Your query logic is fine, but just ensure you’re clearing any cache:

    php
    $args = array(
    ‘posts_per_page’ => -1,
    ‘post_type’ => ‘post’,
    ‘meta_key’ => ‘sum’,
    ‘meta_value’ => ‘100’,
    ‘cache_results’ => false, // Disable caching for real-time results
    ‘update_post_meta_cache’ => false
    );

    $the_query = new WP_Query( $args );
    $the_count = $the_query->found_posts; // More efficient than counting posts
    wp_reset_postdata();

    echo $the_count;
    Why This Works:

    The priority 15 in acf/save_post ensures your calculation runs AFTER ACF has saved the file fields but BEFORE the post save process completes

    Direct field updating with update_field() is more reliable than shortcode processing

    Counting filled fields is more efficient than your array filtering approach

    This should eliminate the two-save requirement and give you real-time completion percentages. The key is ensuring your calculation happens at the right moment in the save sequence.

    Try this approach and let me know if it resolves the timing issue!