Skip to content

Instantly share code, notes, and snippets.

@mariusvetrici
Created February 9, 2015 17:45
Show Gist options
  • Save mariusvetrici/669fed09182502644684 to your computer and use it in GitHub Desktop.
Save mariusvetrici/669fed09182502644684 to your computer and use it in GitHub Desktop.
Synchronize / connect WordPress Post Author field with Advanced Custom Fields (ACF) user field
<?php
function mve_save_task_post_hook($post_id, $post, $update) {
if ($post->post_type != 'task') {
return;
}
// If ACF Customer != Post author, update it
$old_post_author = sanitize_text_field($_REQUEST['post_author']);
$new_post_author = sanitize_text_field($_REQUEST['post_author_override']);
if (isset($new_post_author) &&
$old_post_author != $new_post_author
) {
remove_action("acf/update_value/name=customer", "mve_save_task_update_author_acf_hook");
update_field("customer", $new_post_author);
add_filter('acf/update_value/name=customer', 'mve_save_task_update_author_acf_hook', 10, 3);
}
}
add_action('save_post', 'mve_save_task_post_hook', 10, 3);
function mve_save_task_update_author_acf_hook( $customer_id, $post_id, $field ) {
// Author ACF field changed
if ($customer_id != get_field('customer')["ID"]) {
$my_post = array(
'ID' => $post_id,
'post_author' => $customer_id
);
remove_action('save_post', 'mve_save_task_post_hook');
// Update the post into the database
wp_update_post($my_post);
add_action('save_post', 'mve_save_task_post_hook', 10, 3);
}
return $customer_id;
}
add_filter('acf/update_value/name=customer', 'mve_save_task_update_author_acf_hook', 10, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment