Introduction – Updating ACF Fields with Custom Code When a WordPress Post is Saved:
Advanced Custom Fields (ACF) is a powerful WordPress plugin that allows users to easily customize their websites by adding custom fields to various content types. While ACF provides a user-friendly interface for managing custom fields, there are scenarios where you might need to update ACF fields programmatically when a post is saved. In this blog post, we will explore how to achieve this using custom code.
Step 1: Understanding WordPress Hooks
WordPress provides hooks that allow developers to execute custom code at specific points during the execution of the core software. In our case, we’ll leverage the save_post
hook, which is triggered whenever a post or page is saved or updated.
Step 2: Identifying ACF Field Key
Before writing the code, you need to identify the key of the ACF field you want to update. You can find this key in the ACF field group settings. It usually looks like field_XXXXXX
, where XXXXXX
is a unique identifier for your field.
Step 3: Writing the Custom Code
Now, let’s write the custom code that will be executed when a post is saved. You can add this code to your theme’s functions.php
file or create a custom plugin for it.
function update_acf_field_on_post_save($post_id) {
// Check if this is not an autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
// Check if it's a valid post type (adjust 'post' to your desired post type)
if (!in_array(get_post_type($post_id), array('post', 'page'))) return;
// Replace 'field_XXXXXX' with your ACF field key
$acf_field_key = 'field_XXXXXX';
// Get the value you want to update the ACF field with
$new_field_value = get_post_meta($post_id, '_your_custom_field_key', true);
// Update the ACF field
update_field($acf_field_key, $new_field_value, $post_id);
}
// Hook the function to the save_post action
add_action('save_post', 'update_acf_field_on_post_save');
Make sure to replace 'field_XXXXXX'
with the actual key of your ACF field and adjust the post type if necessary.
Step 4: Testing
After adding the code, save a post or page in your WordPress admin. The custom code should now execute, updating the specified ACF field with the desired value.
Conclusion – Updating ACF Fields with Custom Code When a WordPress Post is Saved:
By using the save_post
hook and custom code, you can update ACF fields programmatically when a post is saved. This approach allows for more flexibility and control over your WordPress site’s content, ensuring that your ACF fields are always up-to-date with the latest information.
If you need help creating code like this for your site get in touch.
Photo by Andre Taissin on Unsplash