0

I have two custom post types, one is the child of the other (the parent is more of a modal post). I want the child post to inherit the same title and slug as its parent.

I've tried to use the following action hook:

function copy_parent_post_title( $post_id ) {

    $new_post = get_post($post_id);

    if($new_post->post_type == 'child-post-type') {

    $parent_title = get_the_title($new_post->post_parent);
    $post_slug = sanitize_title_with_dashes($parent_title);

    $post_update = array(
        'ID'           => $post_id,
        'post_title' => $parent_title,
        'post_name' => $post_slug
    );

            // To stop infinite loop:
    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 that $new_post->post_parent is always giving 0. I've tried replacing it manually with the actual parent ID and the above works fine. Why is $new_post->post_parent not giving the correct parent post ID?

  • why ahould it give anything other then zero? Don't see any reason in your code that it will not be zero. – Mark Kaplun Jan 24 '14 at 10:36
  • it's supposed to give the parent post ID of the post because $new_post is a $post object. Am I missing something? – user1280853 Jan 24 '14 at 10:55
  • I am using WP Types to create the custom post types and to define the relationships there. I see in phpmyadmin in the 'wp_posts' table that the post_parent column is indeed 0. How can I find the ID of the parent post if it is not there? – user1280853 Jan 24 '14 at 11:13
  • father-son hierarchies work only for hierarchical post types. From what you describe it doesn't sound like you are using one. – Mark Kaplun Jan 24 '14 at 18:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.