1

I have a custom post type called "patients". I was using only the post title, but now I need to make a relationship with users.

I made this by creating a custom post field (created by ACF), a relational field showing a type of user. It works nice for the admin, but I also need to insert some posts dynamically. How can I do that?

I added posts (before the need of the relationship) using this:

wp_insert_post(
    array(
        'post_name'  => $p_name,
        'post_title' => $p_name,
        'post_type'  => 'patient'
    ), 
    true 
);
  • You would have to insert post using wp_insert_post function. This function returns the new post ID. Use this ID to add meta fields for the post. – Nilambar Oct 27 '14 at 3:26
1

I'm not sur but I think you had (will probalby help other people as the guy who I was 1hour ago)/have same problem that I just resolve.

You have a custom field and you want to manage an User type field in it ?!

Well, everyone know UPDATE_FIELD, but what I didn't know that if you want to add a user, u just have to give the ID, and not the array structure taht print out when u get this fild (nickname, nicename, displayname...)

update_field('yourfieldkey', arrayofyouruserID, theidofyourrelatedpost);

My code to manage (add/delete) new user in relation with the post :

/* remake the memberassigned list*/
$ticket_users = get_field('tickets_assignedto', $thispost_id);
$new_assignedmembersID = array();
if ( $ticket_users != '' ) {
   foreach ($ticket_users as $ticket_user) {
       if ( $ticket_user['ID'] != $member_id ) {
            $new_assignedmembersID[] = $ticket_user['ID'];
       } 
   }
}

if ( $byeorhi == 'member_unassigned') {
    $new_assignedmembersID[] = $member_id;
}

update_field('field_54b8d8b213289',  $new_assignedmembersID,  $thispost_id);
0

As suggested in the comments by @Nilambar, wp_insert_post returns the ID of the post it created. So:

$new_patient = wp_insert_post(
    array(
        'post_name'  => $p_name,
        'post_title' => $p_name,
        'post_type'  => 'patient'
    ), 
    true 
);

Then used the returned ID to create your relationships, add your meta and terms, etc.

  • I already know wp_insert_post returns the new created post ID. My problem is how to replicate the functioning of my form which uses a custom post field. – Marcelo Assis Oct 27 '14 at 16:21

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.