TechEarl

Useful Things You Can Do with acf/save_post

acf/save_post is the hook that fires after ACF saves a post's custom fields. Useful patterns: derived field computation, taxonomy sync, search-index refresh, ACF-to-meta mirroring, validation, audit logging, refreshing posts when a taxonomy term changes (saved_term). Plus the gotchas.

Ishan KarunaratnePublished ⏱️ 12 min readUpdated
Share thisCopied
acf/save_post patterns with code: derived fields, taxonomy sync, search-index refresh, meta mirroring, validation, and refreshing posts on saved_term.

acf/save_post fires right after ACF saves a post's custom field values. It is the canonical hook for any logic that needs to run in response to ACF field changes: computing derived fields, syncing data to taxonomy terms, refreshing a search index, mirroring ACF data into standard WordPress meta, validating field combinations, audit logging. Its mirror image, refreshing posts when a taxonomy term they depend on is edited, uses core's saved_term hook and is covered at the end. The directory sites I run lean heavily on this hook for keeping derived data in sync across thousands of posts.

Jump to:

The hook signature and priorities

php
add_action( 'acf/save_post', 'te_save_handler', 20 );

function te_save_handler( $post_id ) {
    // $post_id is the post ID, or "option" for options pages,
    // or "user_42", "term_5", etc. depending on context.

    // Bail on autosaves and revisions
    if ( wp_is_post_autosave( $post_id ) ) return;
    if ( wp_is_post_revision( $post_id ) ) return;

    // Optional: bail on specific post types
    if ( get_post_type( $post_id ) !== 'listing' ) return;

    // Read the just-saved values
    $price = get_field( 'price', $post_id );
    // ... do work
}

The priority argument matters. Priority 10 (the default) fires BEFORE ACF has saved the meta. Priority 20+ fires AFTER, which is what you want in 99% of cases. Always use priority => 20 so get_field() inside the callback returns the new values, not the old ones.

acf/save_post fires for posts, options pages, user profile updates, taxonomy term edits, and comment metadata edits. The $post_id argument tells you which context. Check is_numeric( $post_id ) or strpos( $post_id, 'option' ) === 0 to branch on context.

Pattern 1: Computing derived fields

The classic use case. You have two ACF fields that together imply a third value, and you want the third value stored so queries can use it directly.

php
add_action( 'acf/save_post', function ( $post_id ) {
    if ( get_post_type( $post_id ) !== 'product' ) return;

    $price = (float) get_field( 'price', $post_id );
    $discount_pct = (float) get_field( 'discount_pct', $post_id );

    if ( $price > 0 && $discount_pct > 0 ) {
        $final = $price * ( 1 - ( $discount_pct / 100 ) );
        update_field( 'final_price', $final, $post_id );
    }
}, 20 );

Why store the derived value rather than compute on read? Performance. If final_price is what WP_Query sorts and filters by, it has to be a stored meta value. Computing on read works for display; it does not work for queries.

Pattern 2: Syncing ACF values to taxonomy terms

Common on directory sites: an ACF field stores a single value that should also be reflected as a taxonomy assignment. The taxonomy can be queried efficiently by WP_Query; the ACF value cannot.

php
add_action( 'acf/save_post', function ( $post_id ) {
    if ( get_post_type( $post_id ) !== 'listing' ) return;

    $state = get_field( 'address_state', $post_id );
    if ( empty( $state ) ) return;

    // Find or create the term in the "location" taxonomy
    $term = term_exists( $state, 'location' );
    if ( ! $term ) {
        $term = wp_insert_term( $state, 'location' );
    }

    if ( ! is_wp_error( $term ) ) {
        wp_set_post_terms( $post_id, [ (int) $term['term_id'] ], 'location', false );
    }
}, 20 );

The user edits the ACF field; the taxonomy stays in sync. Queries that filter by state can now use tax_query instead of slower meta_query. The reverse direction matters too: when someone renames or edits the term itself, the posts that reference it often need to recompute derived data, which is what the saved_term hook for refreshing posts on a taxonomy change is for.

Pattern 3: Triggering a search-index refresh

If you maintain an Elasticsearch or Algolia index of your posts, acf/save_post is the right place to enqueue a re-index of the changed post:

php
add_action( 'acf/save_post', function ( $post_id ) {
    if ( ! is_numeric( $post_id ) ) return; // options/users don't get indexed
    if ( get_post_status( $post_id ) !== 'publish' ) return;

    // Schedule the re-index via WP-Cron rather than running synchronously
    wp_schedule_single_event( time() + 10, 'te_reindex_post', [ (int) $post_id ] );
}, 20 );

add_action( 'te_reindex_post', function ( $post_id ) {
    // Push the post to the search index
    te_search_indexer()->index_post( $post_id );
} );

Scheduling the re-index for a few seconds later means the editor saves the post and gets a fast response, while the indexer runs asynchronously via WP-Cron. If your index is ElasticPress, keeping it fresh on save is what makes running WP_Query through ElasticPress return current results instead of stale ones.

Pattern 4: ACF-to-postmeta mirroring for query performance

For ACF fields you query against frequently with meta_query, mirroring the value into a standard _meta key with an explicit type can be much faster:

php
add_action( 'acf/save_post', function ( $post_id ) {
    if ( get_post_type( $post_id ) !== 'listing' ) return;

    $price = (float) get_field( 'price', $post_id );

    // Store as a numeric meta key for fast NUMERIC compare queries
    update_post_meta( $post_id, '_price_numeric', $price );
}, 20 );

Then your queries hit _price_numeric with a NUMERIC compare, which the database handles much more efficiently than ACF's default storage. The cost is the extra meta row per post; the benefit is queries that scale.

Pattern 5: Cross-field validation

Sometimes a save should be partially undone or flagged because two field values do not validate together:

php
add_action( 'acf/save_post', function ( $post_id ) {
    if ( get_post_type( $post_id ) !== 'event' ) return;

    $start = get_field( 'start_date', $post_id );
    $end = get_field( 'end_date', $post_id );

    if ( $start && $end && strtotime( $end ) < strtotime( $start ) ) {
        // End date is before start; reset it to the start date and log
        update_field( 'end_date', $start, $post_id );
        error_log( "Reset end_date < start_date on post $post_id" );
    }
}, 20 );

This is corrective, not preventive. For preventive validation (refusing the save entirely), use acf/validate_value filters per field rather than acf/save_post.

Pattern 6: Audit logging

For directory sites with editorial oversight or compliance requirements, logging every ACF field change is straightforward:

php
add_action( 'acf/save_post', function ( $post_id ) {
    if ( ! is_numeric( $post_id ) ) return;

    $user = wp_get_current_user();
    $changes = []; // could diff against old values from a pre-save hook

    error_log( sprintf(
        '[acf-audit] post=%d user=%s post_type=%s',
        $post_id,
        $user->user_login,
        get_post_type( $post_id )
    ) );
}, 20 );

For real audit logging, capture the before/after diff in an acf/save_post at priority 10 (before save, to read old values) and then at priority 20 (after save, to read new values) and store the diff in a custom audit table.

Gotchas

Recursive update_field calls. If your acf/save_post callback calls update_field(), that triggers another acf/save_post. Without a guard, this is an infinite loop. The fix:

php
add_action( 'acf/save_post', function ( $post_id ) {
    static $running = [];
    if ( isset( $running[ $post_id ] ) ) return;
    $running[ $post_id ] = true;

    update_field( 'derived_value', 'something', $post_id );

    unset( $running[ $post_id ] );
}, 20 );

Priority 10 vs 20. Always use 20 unless you specifically need the pre-save state. Priority 10 callbacks see the OLD values when reading via get_field().

Options pages and user updates fire too. Check $post_id context and bail on contexts you do not handle.

Bulk imports trigger the hook repeatedly. If you run a 10,000-post import script, your acf/save_post callback runs 10,000 times. Make sure it is fast or use remove_action to temporarily detach during bulk operations.

The hook does NOT fire when posts are updated via wp_insert_post or wp_update_post directly without ACF metadata. It only fires when ACF is actively saving its meta. For pure post-update workflows, use save_post instead.

Refresh posts when a taxonomy term changes

acf/save_post reacts to a post save. The reverse case catches people out: editing a taxonomy term (renaming a category, fixing a term description, updating a term's ACF meta) updates the term row and clears the term cache, but it does not touch any post that has baked that term's data into cached output. The fix is to hook saved_term, find the posts attached to the term, and re-save them so their post-level caches regenerate:

php
add_action( 'saved_term', 'te_refresh_posts_on_term_save', 10, 3 );

function te_refresh_posts_on_term_save( $term_id, $tt_id, $taxonomy ) {
    $posts = get_posts( array(
        'post_type'     => 'any',
        'post_status'   => 'publish',
        'numberposts'   => 1,
        'cache_results' => false,
        'tax_query'     => array(
            array(
                'taxonomy' => $taxonomy,
                'field'    => 'term_id',
                'terms'    => $term_id,
            ),
        ),
    ) );

    if ( ! empty( $posts ) ) {
        wp_update_post( $posts[0] );
    }
}

That surgical version re-saves one representative post per term edit. Be clear about what that buys: the re-save clears that one post's core caches and fires save_post, so it only refreshes a shared, per-term fragment if something on your site purges that fragment from save_post (many page-cache plugins purge the post's term archives on save; a hand-rolled transient does not). When you own the fragment, skip the proxy and delete it directly, keyed by the term:

php
add_action( 'saved_term', function ( $term_id, $tt_id, $taxonomy ) {
    // The same key the template used when it cached the fragment.
    delete_transient( "te_term_fragment_{$taxonomy}_{$term_id}" );
}, 10, 3 );

When a term edit leaves posts stale

A theme that reads the term fresh on every request (get_the_category()) picks up the new value on its own. The problem only appears when a post's output derives from term data and that output is cached. Cases I have hit:

  • Post markup bakes in a term's name or description and sits in a persistent object cache or a transient.
  • The post renders ACF or term meta attached to the term, cached per post.
  • A full-page HTML cache or CDN edge cache serves a snapshot with the old term text.
  • A search index (Elasticsearch, Algolia) stores a flattened copy of the post with its term names, and nothing re-indexes the post when only the term changed.

How saved_term works

WordPress 5.5 (August 2020) added saved_term as the "after the dust has settled" hook: it fires after the term has been written and after the term cache has been cleared, so the callback sees the new term state. It passes five arguments:

php
do_action( 'saved_term', $term_id, $tt_id, $taxonomy, $update, $args );

$term_id and $tt_id are the term and term-taxonomy IDs, $taxonomy is the slug, $update is true for an edit and false for a newly created term, and $args holds the arguments passed to the create or update call. saved_{$taxonomy} (for example saved_category) is the per-taxonomy variant. On installs older than 5.5 the fallback is the edited_term and created_term pair, which fire before the cache clear and are fiddlier to reason about.

If you tried save_post first, that is the trap: when an editor changes only a post's terms in the block editor, the post row saves on one request and the term assignments arrive through a separate wp/v2 request, so a save_post callback can read the post with its old terms. When the trigger genuinely is a post edit through the block editor, rest_after_insert_{$post_type} (for example rest_after_insert_post) fires once the post and all its meta and terms have saved. Keep saved_term for term edits.

Why re-saving the post busts the cache

wp_update_post() runs the whole normal invalidation path: it fires save_post and save_post_{$post_type}, bumps the modified time, and triggers core's post-cache cleanup. Fragment caches, page-cache purges, CDN purge hooks and search re-indexers (ElasticPress included, see running WP_Query through ElasticPress) almost all hang off save_post, so you do not need to know which cache holds the stale value. Passing the post object is enough; the re-save itself is the trigger.

That fan-out is also a recursion risk, the same one as in the gotchas above, but only in one shape. saved_term fires when a term itself is written (wp_insert_term(), wp_update_term()), not when a post's term assignments change, so a save_post callback that merely re-assigns terms with wp_set_object_terms() does not trigger it. The loop appears when a save_post callback edits the term itself, for example writing a count or a description back with wp_update_term(): that fires saved_term, which re-saves the post, which edits the term again, spamming the revisions table on the way. Unhook your callback around the wp_update_post() call (remove_action() before, add_action() after) or use a static reentrancy flag.

Re-saving many posts at scale

A popular term can hold thousands of posts. Looping wp_update_post() over all of them inside the saved_term request makes the admin save hang, likely hit PHP's max_execution_time, and hammer the database: a self-inflicted outage triggered by someone fixing a typo. So decide what you need:

  • A shared, per-term cache fragment: delete the fragment directly, or re-save one representative post if your save_post purge wiring is what clears it (the snippets above).
  • Per-post output that each embeds the term: touch every post, but asynchronously through WP-Cron, Action Scheduler or a WP-CLI loop.
php
add_action( 'saved_term', 'te_queue_posts_on_term_save', 10, 3 );

function te_queue_posts_on_term_save( $term_id, $tt_id, $taxonomy ) {
    $ids = get_posts( array(
        'post_type'     => 'any',
        'post_status'   => 'publish',
        'numberposts'   => 200,
        'fields'        => 'ids',
        'cache_results' => false,
        'tax_query'     => array(
            array(
                'taxonomy' => $taxonomy,
                'field'    => 'term_id',
                'terms'    => $term_id,
            ),
        ),
    ) );

    foreach ( $ids as $post_id ) {
        // Action Scheduler: spreads the writes out instead of doing them now.
        as_enqueue_async_action( 'te_refresh_single_post', array( $post_id ) );
    }
}

add_action( 'te_refresh_single_post', function ( $post_id ) {
    wp_update_post( array( 'ID' => $post_id ) );
} );

'cache_results' => false keeps the lookup from flooding the object cache, and the numberposts cap of 200 stops a runaway term from queuing a hundred thousand jobs at once. On a really large catalog I page through the IDs over several cron ticks. Most sites never need any of this; reach for it only once you have confirmed post output is caching term data and going stale. General slowness is a different problem, covered in common ACF performance problems at scale.

The term-refresh plugin

I keep this in a small site-specific plugin or mu-plugins, never the theme: it is infrastructure, and a theme switch would silently disable it.

php
<?php
/**
 * Plugin Name: TE Refresh Posts On Term Save
 * Plugin URI:  https://techearl.com/acf-save-post-hook-example
 * Description: Re-saves posts attached to a taxonomy term when the term is edited, so post-level caches that embed term data refresh.
 * Version:     1.0.0
 * Author:      Ishan Karunaratne
 * Author URI:  https://techearl.com
 * License:     GPL-2.0-or-later
 * Text Domain: te-refresh-on-term-save
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

add_action( 'saved_term', 'te_refresh_posts_on_term_save', 10, 4 );

function te_refresh_posts_on_term_save( $term_id, $tt_id, $taxonomy, $update ) {
    // A brand-new term has no posts yet, so there is nothing to refresh.
    if ( ! $update ) {
        return;
    }

    $posts = get_posts( array(
        'post_type'     => 'any',
        'post_status'   => 'publish',
        'numberposts'   => 1,
        'cache_results' => false,
        'tax_query'     => array(
            array(
                'taxonomy' => $taxonomy,
                'field'    => 'term_id',
                'terms'    => $term_id,
            ),
        ),
    ) );

    if ( ! empty( $posts ) ) {
        wp_update_post( $posts[0] );
    }
}

The $update check skips the query when a term is first created. Restricting post_type to the types the taxonomy is registered against, instead of 'any', narrows it further.

Verify the term refresh

  • Modified time: edit a term, then wp post get <id> --field=post_modified on a post in that term; the timestamp should have just moved.
  • Front end: load the post and confirm the new term value shows. With a full-page cache, this proves the save_post purge fired.
  • Log once: a temporary error_log() with $term_id and the matched-post count confirms the hook fired with the right arguments. Remove it before shipping.
  • Big terms: with the batched version, the admin request should return instantly and the jobs drain over the next few cron runs.

If nothing refreshes, the usual culprits are a tax_query matching no posts (wrong field, or a term with zero posts), a callback registered with too few accepted args (so $taxonomy arrives empty), or a page cache that is not wired to purge on save_post.

For the broader pattern of programmatic ACF mutations from PHP scripts and WP-CLI, see How to Update ACF Fields Programmatically and Using AI with WP-CLI for Faster WordPress Operations.

When a save hook misbehaves and you need someone else to look at it, share the snippet somewhere it can actually run rather than pasting it into a chat window: the recursion is much easier to see when the reader can press Run.

WordPress 5.5 or newer. saved_term was introduced in 5.5 (August 2020) and fires after the term has been written and the term cache cleared. On older installs, fall back to edited_term and created_term, which fire before the cache clear.

Not synchronously. Looping wp_update_post() over thousands of posts inside the term-save request hangs the admin and can time out. For a shared per-term cache, delete that fragment directly (or re-save one representative post if your save_post purge clears it), or queue the post IDs and process them in the background with WP-Cron, Action Scheduler, or a WP-CLI loop.

Sources

Authoritative references this article was fact-checked against.

TagsWordPressACFHooksPHPTaxonomyCaching

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

How hashcat rule functions mutate wordlist words, the best64 ruleset with real output, stacking rules, writing your own, and the big public rulesets. Tested on hashcat 7.1.2.

Hashcat Rules: More Cracks From the Same Wordlist

Rules are the highest-yield technique in cracking: one wordlist word becomes hundreds of plausible variants. I cover the rule functions, best64 with real generated output, stacking, writing your own, and the big public rulesets. Tested on hashcat 7.1.2.

LUKS disk encryption with cryptsetup on Linux: luksFormat to encrypt a block device, luksOpen to unlock it, then mkfs and mount. Includes header backup and keyslot management.

LUKS Disk Encryption With cryptsetup

Set up LUKS disk encryption with cryptsetup: format a block device, open it, put a filesystem on it, and mount it. The four commands, plus the header backup nobody warns you about.