Get custom fields values in filter on wp_insert_post_data Get custom fields values in filter on wp_insert_post_data wordpress wordpress

Get custom fields values in filter on wp_insert_post_data


Tweak to Riadh's accepted answer (would add as a comment but haven't got enough rep yet):

As documented in the WordPress Codex wp_update_post includes the save_post hook so calling wp_update_post() inside the save_post hook creates an infinite loop. To avoid this, unhook then rehook your function like so:

add_action('save_post', 'change_title');function change_title($post_id) {    $time = get_field('time',$post_id);    $post_title = 'Topic created at '. $time;    // unhook this function so it doesn't loop infinitely    remove_action('save_post', 'change_title');    // update the post, which calls save_post again    wp_update_post(array('ID' => $post_id, 'post_title' => $post_title));    // re-hook this function    add_action('save_post', 'change_title');}    


You can actually access the global $_POST variable for your field value , but i guess you can do it in a cleaner way by using the save_post action to update your post's title, eg:

add_action('save_post', 'change_title');function change_title($post_id) {    $time = get_field('time',$post_id);    $post_title = 'Topic created at '. $time;    // unhook this function so it doesn't loop infinitely    remove_action('save_post', 'change_title');    // update the post, which calls save_post again    wp_update_post(array('ID' => $post_id, 'post_title' => $post_title));    // re-hook this function    add_action('save_post', 'change_title');}  

assuming that your ACF fieldname is "time".

Edit: Updated the answer as per Mark Chitty's answer.


You may try this

add_filter( 'wp_insert_post_data', 'change_title', '99', 2 );function change_title($data , $postarr){    $custom_field = 'custom_filed_name';    $post_id = $postarr['ID'];    $time = get_post_meta( $post_id, $custom_field, true );    // Now you have the value, do whatever you want}