Hi all, thanks for reading.
Environment :
WordPress + Advanced Custom Fields plugin
Problem :
I have searched for hours now and I can’t seem to find the correct syntax to do the following:
When posting a new post, get custom field value in order to automatically replace the title of the post by that value. Example: I create a post and set ’10am’ in my ‘time’ custom field. The title of the post is automatically replaced by ’10am’.
Example:
So I’m adding a filter with the following :
add_filter('wp_insert_post_data', 'change_title') ;
function change_title($data)
{
$time = XXX ; // How should I get this custom field value ?
$new_title = 'Topic created at'.$time ;
$data['post_title'] = $time ;
return $data;
}
It must be very simple but I have tried every function available on both WP and the plugin’s documentations. I would be very thankful if anyone passing by gave me the solution.
Thanks in advance !
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 thesave_post
hook so callingwp_update_post()
inside thesave_post
hook creates an infinite loop. To avoid this, unhook then rehook your function like so: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:
assuming that your ACF fieldname is “time”.
Edit: Updated the answer as per Mark Chitty’s answer.
You may try this
Advanced Custom Fields creates a ‘field key’ for each custom field that is created. I was able to refer to this key value when trying to access the custom fields. The field key value can be found by viewing page source when viewing the post type within the WordPress admin section.
Look for
data-field-key
. You will see a value similar todata-field-key="field_5847b00820f13"
in the page source. Use this value when accessing the value in the$postarr
argument in thewp_insert_post_data
filter. The custom fields will be in a nested array namedfields
within the$postarr
argument.Alternatively, the field key value can be located by navigating to the Advanced Custom Fields / Export option from within the admin section. Once you are on the export page for Advanced Custom Fields, select the export to PHP option and you will see the value in the resulting PHP code.
In the example below, I am concatenating two Advanced Custom Fields and updating the
post_title
in the$data
array returned from the function.The result is that the
post_title
value will be saved to the database via the built in WordPress save post logic.