I'm trying to make a function where a child post of a certain post type inherits the same title and slug as its parent. I'm using WP Types to define my post types and their relationships. But I'm having trouble with the below code:
function copy_parent_post_title( $post_id ) {
$new_post = get_post($post_id);
if($new_post->post_type == 'carnews-adverts') {
$parent_id = get_post_meta( $post_id, '_wpcf_belongs_carnews_id', true );
$parent_title = get_the_title($parent_id);
$post_slug = sanitize_title_with_dashes($parent_title);
$post_update = array(
'ID' => $post_id,
'post_title' => $parent_title,
'post_name' => $post_slug
);
remove_action( 'wp_insert_post', 'copy_parent_post_title' );
wp_update_post( $post_update );
add_action( 'wp_insert_post', 'copy_parent_post_title' );
}
}
add_action( 'wp_insert_post', 'copy_parent_post_title' );
The problem is this line:
$parent_id = get_post_meta( $post_id, '_wpcf_belongs_carnews_id', true );
I presume it is because at this point the post's meta data hasn't been inserted into the database yet? If so how can I achieve what I want by accessing the get_post_meta upon inserting a post?
Thanks
wp_insert_post
runs very late. I'd expect this to work but there may be something peculiar about that plugin. What have you done to debug this? Exactly what is happening when you run the code?