phpwordpressadvanced-custom-fieldscustom-post-typeultimate-member

How do I display custom post title as "first_name last_name"


I have created a site whereby athletes can register and create their own templated profile page. On registration, I automatically create a custom post (their profile) and set the user as the author of that post.

However, I cannot for the life of me set the post title as the user's (now author's) first name and surname. For instance, if John Smith registers, I would like the post title to read John Smith, and the slug to convert to athlete/john.smith.

I have used $user_info->nickname for now, but this causes both the title and the slug to read as john.smith

This is the code I am using -any pointers would be greatly appreciated:

add_action( 'user_register', 'wpse_216921_company_cpt', 10, 1 );

function wpse_216921_company_cpt( $user_id )
{
    // Get user info
    $user_info = get_userdata( $user_id );
    $user_roles = $user_info->roles;

    // New code added 
    $this_user_role = implode(', ', $user_roles );

    if ($this_user_role == 'author') {

        // Create a new post
        $user_post = array(
            'post_title'   => $user_info->nickname,
            'post_status'  => 'publish', // <- here is to publish
            'post_type'    => 'athlete', // <- change to your cpt
            'post_author'  => $user_info->ID
        );
        // Insert the post into the database
        $post_id = wp_insert_post( $user_post );
    }
}

Solution

  • You should also use post_name for slug(john.smith) and first_name,last name for post title like this:

    add_action( 'user_register', 'wpse_216921_company_cpt', 20, 1 );
    
    function wpse_216921_company_cpt( $user_id )
    {
        // Get user info
        $user_info = get_userdata( $user_id );
        $user_roles = $user_info->roles;
    
        // New code added 
        $this_user_role = implode(', ', $user_roles );
    
        if ($this_user_role == 'author') {
            
            $post_title = $user_info->first_name.' '.$user_info->last_name;
            $post_title = trim(ucwords($post_title));
            $post_slug  = preg_replace('/\s+/', '.', $post_title);
    
            // Create a new post
            $user_post = array(
                'post_title'   => $post_title, //$user_info->display_name,
                'post_name'    => $post_slug,
                'post_status'  => 'publish', // <- here is to publish
                'post_type'    => 'athlete', // <- change to your cpt
                'post_author'  => $user_info->ID
            );
            // Insert the post into the database
            $post_id = wp_insert_post( $user_post );
        }
    }