Last active
January 18, 2022 16:23
-
-
Save chriswagoner/c84833d5ebec697986e15e10881e75e0 to your computer and use it in GitHub Desktop.
Get Field and Update ACF Field on Post Save
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In this example we are getting a checkbox and dropdown field (noted below) and then calculating the sum. Then, we update a custom field with the total. | |
add_action( 'save_post', 'custom_field_calc', 20, 2 ); | |
function custom_field_calc( $id, $post ) { | |
// bail out if this is an autosave | |
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { | |
return; | |
} | |
// bail out if this is not a catalog item | |
if ( $post->post_type != 'custom-cpt' ) { // Put your Custom Post Type slug here | |
return; | |
} | |
// ... do override stuff | |
global $post; | |
$post_id=$post->ID; | |
$group = get_field('mygroup'); // Here we are using a Group field, below are the group's subfields | |
$myfield1 = $group['field1']; | |
$myfield2 = $group['field2']; | |
$myDropdown = get_field('my_dropdown'); // This is a dropdown field and we're using a switch to set the value based on the selection. | |
switch ($myDropdown) { | |
case "Option 1": | |
$dropdownValue = '0'; | |
break; | |
case "Option 2": | |
$dropdownValue = '10'; | |
break; | |
case "Option 3": | |
$dropdownValue = '20'; | |
break; | |
default: | |
$dropdownValue = '0'; | |
} | |
$totalValue = $myfield1 + $myfield2 + $myDropdown; // Calculate everything from above | |
update_post_meta($post_id, 'fieldToUpdate', $totalValue); // update a custom field | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment