0

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

1

Maybe you can move all the logic to added_post_meta & 'updated_postmeta' hooks.

add_action( 'added_post_meta', 'update_carnews_adverts_aprent', 10, 4 );
add_action( 'updated_postmeta', 'update_carnews_adverts_aprent', 10, 4 );

function( $meta_id, $object_id, $meta_key, $meta_value ) {
  if ( $meta_key !== '_wpcf_belongs_carnews_id' || ! is_numeric($meta_value) ) return;
  $post = get_post( $object_id );
  if ( $post instanceof WP_Post && $post->post_type == 'carnews-adverts' ) {
    $parent = get_post( $meta_value );
    if ($post->post_title !== $parent->post_title || $post->post_name !== $parent->post_name) {
       $post_update = array(
          'ID'         => $post->ID,
          'post_title' => $parent->post_title,
          'post_name' => $parent->post_name
       );
       wp_update_post( $post_update );
    }
  }
}
| improve this answer | |

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.