how can i create php function where i can create a post in one custom post type also create a child post type, i have already create a parent post type, i.e

post type "a = car"
post type "b = user"

i want to create a post in custom post type "a = car" but also add new post in post type "b = user" using wp_insert_post

this is the closest i have found http://wordpress.org/support/topic/setting-post_parent-during-wp_insert_post

1 Answer 1


If I understand well you want use wp_insert_post to create a post of 'car' type, and the when this post is created, use the id of this post as parent for another post, but of another post tpye: 'user'.

This is possible, but note that if one post type is hierachical your permalinks will break.

First of all you need to create 2 arrays for the 2 post, of course for the post 'user' at first time you do not set the post_parent because you still do not know it.

$car = array (
  'post_title' => 'A Car'
  'post_content' => 'This is a beautiful car!'
  'post_type' => 'car'

$user = array(
  'post_title' => 'An User'
  'post_content' => 'Hi, I am the user of the beautiful car'
  'post_type' => 'user'

After that you insert the first post (the parent) using wp_insert_post. Once this function return the id of the just inserted post, then you use it to insert the child post, using that id as post_parent.

You can write a custom function:

function create_car_and_user( $car, $user ) {

    if ( empty( $car ) || empty( $user ) ) return false;

    $car_id = wp_insert_post( $car );

    if ( $car_id > 0 ) { // insert was ok

      $user['post_parent'] = $car_id;
      $user_id = wp_insert_post( $user );

      return array( $car_id, $user_id );

    } else {

       return false;



That function accept as arguments the 2 arrays created before and if everithing goes fine, return another array of two element, where first element is the id of the car post just inserted, the second element is the id of the user post just inserted.

If something goes wrong function return false. If als possible that function return an array, where firs element is car id, and second is false: in that case insertion of car goes fine, insertion of user not.

  • thanks , would it be possible to show me the code in a php function where i can pass the values and it would run the script.
    – user5601
    Oct 11, 2013 at 19:35
  • @user5601 I've updated my answer.
    – gmazzap
    Oct 11, 2013 at 20:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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