I’m trying to build the title of a custom post using the values within post custom fields. The problem is that using title_save_pre
only executes when I update the post, not when I create it.
When I create the post I get the title : (no title)
If I edit and save I get the right title.
I need to get the right title in backend.
This is my code:
function update_phone_title($title) {
global $post;
$type = get_post_type($post->ID);
if ( 'phone' == $type) {
$title = get_post_meta($post->ID, 'manufacturer', TRUE);
$title .= ' '.get_post_meta($post->ID, 'model', TRUE);
$title .= ' '.get_post_meta($post->ID, 'memory', TRUE);
}
return $title;
}
add_filter ('title_save_pre', 'update_phone_title');
FIXED using wp_insert_post_data .I did it with this code:
function filter_handler( $data , $postarr )
{
global $post;
$id = $post->ID;
if('phone' == $data['post_type'] && isset($data['post_type']))
if($id) {
$title = $_POST['fields']['field_4fd2897fc0bfe']. ' ' . $_POST['fields']['field_4fd2897fc2328'] . ' ' .$_POST['fields']['field_4fd2897fc273a'];
$data['post_title'] = $title;
}
return $data;
}
add_filter( 'wp_insert_post_data' , 'filter_handler' , '99', 2 );
The filter
title_save_pre
runs before the post is written to the database, and also before any of its post meta is saved to the database. Soget_post_meta
at this point will be blank for the first run, and always return ‘old’ data.To correct this you’ll want to hook into
save_post
and update the post from there.save_post
runs after the post has been saved to the database, and the in-built ‘custom fields’ have been saved.To do this you can use
wp_update_post
. However, you’ll need to be careful:One way round this is to remove the
save_post
callback from the hook inside the callback, as demonstrated here.