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

Automatically create a post for each user using wp_insert_post


I'm looking to automatically create a post in a custom post type ( jt_cpt_team ) for each user with at least Author credentials.

Primarily, it needs to do this for each new user created by an admin. If there is an easy way to generate a post for each of the exiting authors (~30) then that's great, but I don't mind doing these by hand if needs be.

I'm guessing this is more-or-less what I need — struggling to get it to work though…

class team_functions {

  public function __construct() {

    add_action('user_register', array($this, 'create_authors_page'));

  }

  public function create_authors_page($user_id) {

    $the_user      = get_userdata($user_id);
    $new_user_name = $the_user->user_login;
    $my_post       = array();
    $my_post['post_title']   = $new_user_name;
    $my_post['post_type']    = 'jt_cpt_team';
    $my_post['post_content'] = '';
    $my_post['post_status']  = 'publish';
    $my_post['post_theme']   = 'user-profile';

    wp_insert_post( $my_post );

  }

}

Moreover, if there's a way to add the author's email as a custom_field that would be awesome.

Thanks in advance for all your help :)


Solution

  • Something like this should work:

    public 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;
    
        $my_post = array( 'post_title'   => $new_user_name,
                          'post_type'    => 'jt_cpt_team',
                          'post_content' => '',
                          'post_status'  => 'publish',
                          'post_theme'   => 'user-profile',
                          'guid'         => $PostGuid );
    
        $NewPostID = wp_insert_post( $my_post ); // Second parameter defaults to FALSE to return 0 instead of wp_error.
    
         // To answer your comment, adding these lines of code before the return should do it (Have not tested it though):
         $Key   = $new_user_name; // Name of the user is the custom field KEY
         $Value = $user_id; // User ID is the custom field VALUE
         update_post_meta( $NewPostID, $Key, $Value );
    
         return $NewPostID;
         }