I need the "auteur" title post to be populated by the the "auteur-name" custom field. I guess I need something similar to this, but I am not using the CRED plugin. Thanks
add_action('cred_save_data', 'custom_title',10,2);
function custom_title($post_id, $form_data)
{
// if a specific form
if ($form_data['id']==319)
{
// Update post 37
$title = $_POST['wpcf-name-auteur'];
$my_post = array(
'ID' => $post_id,
'post_title' => $title,
);
// Update the post into the database
wp_update_post( $my_post );
}
Hi Charles,
Thank you for contacting us and I'll be happy to assist.
To automatically update the post title, using a custom field value, you can use "wp_insert_post_data" function:
( ref: https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data )
add_filter( 'wp_insert_post_data' , 'set_auto_title_auteur_fn' , '99', 2 );
function set_auto_title_auteur_fn( $data, $postarr )
{
if( $data['post_type'] == 'auteur' ) {
// get the value from the field
$field_value = $postarr['wpcf']['name-auteur'];
//Updates the post title to the new value
$data['post_title'] = $field_value ;
}
return $data; // Returns the modified data.
}
Note: Please update "auteur" and "name-auteur" to match the actual post's slug and the custom field's slug respectively.
I hope this helps.
regards,
Waqar
Thanks I uploaded the code in function.php but with the code implemented all the necessary fileds are not showing when adding a new "Auteur" - see attached images with and without the code.
Hi Charles,
Thanks for sharing the update and the screenshots.
To avoid this issue (which appears only when adding a new post and not editing existing ones), you can slightly update line# 4 in the code snippet, I shared earlier.
Old:
if( $data['post_type'] == 'auteur' ) {
Updated:
if( ($data['post_type'] == 'auteur') && ($data['post_status'] != 'auto-draft') ) {
This should make the code work properly when a new post item is being added.
regards,
Waqar
We get a regular new post (auteur) page, but the title is not populated by the field "nom-auteur".
Here is the new implemented code:
// Auto populate title for auteur
add_filter( 'wp_insert_post_data' , 'set_auto_title_auteur_fn' , '99', 2 );
function set_auto_title_auteur_fn( $data, $postarr )
{
if( ($data['post_type'] == 'auteur') && ($data['post_status'] != 'auto-draft') ) {
// get the value from the field
$field_value = $postarr['wpcf']['name-auteur'];
//Updates the post title to the new value
$data['post_title'] = $field_value ;
}
return $data; // Returns the modified data.
}
Thanks
Hi Charles,
Can you please make sure that code is using the exact custom field slug?
If the field's slug is "nom-auteur", the same should be used in the code too.
( screenshot: hidden link )
Note: To see the actual slug set for the custom field, you can go to WP Admin -> Toolset -> Custom Fields.
regards,
Waqar
My issue is resolved now. Thank you!