Search code examples
wordpresscustom-post-typedynamically-generateduser-registration

Automatically create a post for each user on wordpress site


I'm trying to automatically create a custom post (users) upon registering a new user to my site. I'm just barely familar with php, but I've been working from another question from stackoverflow: Automatically create a post for each user using wp_insert_post

I would ideally love to create a page that carries over custom fields upon registering or updating user information. I've used ACF to create custom fields that are associated with; users (listed in the code as lowercase variables), and the to-be-created custom posts (listed in the code as uppercase variables).

function create_authors_page( $user_id ) {

$the_user           = get_userdata( $user_id );
$new_user_name      = $the_user->user_login;
$PostSlug           = $user_id;
$PostGuid           = home_url() . "/" . $PostSlug;
$member_bio         = get_field('member_bio');
$contact_info       = get_field('contact_info');
$member_affiliation = get_field('member_affiliation');

$my_post = array( 'post_title'   => $new_user_name,
                  'post_type'    => 'users',
                  'post_content' => '',
                  'post_status'  => 'publish',
                  'post_theme'   => 'user-profile',
                  'guid'         => $PostGuid );

$NewPostID = wp_insert_post( $my_post ); 
 $Member_Bio            = $member_bio; 
 $Contact_Info          = $contact_info; 
 $Member_Affiliation    = $member_affiliation;
 update_post_meta( $NewPostID, $Member_Bio, $Contact_Info, $Member_Affiliation );

 return $NewPostID;
 }

add_action('publish_members', 'create_authors_page');


Solution

  • Your hook is incorrect, use user_register action hook which fires after a user has registered and passes $user_id as a variable:

    add_action('user_register', 'create_authors_page');
    function create_authors_page( $user_id ) {
        // do your stuff
    }
    

    You can also use profile_update hook that trigger each time user update profile.