WordPress - Use user meta for if else statement in 'user_register' hook

Viewed 70

I am trying to access user meta by $wpdb query after a user registers. What I am trying to do is to make 2 different custom post types if a user is a freelancer or an employer.

here is the code:

add_action('user_register','registration_funtion', 999);
function registration_funtion($uid){
global $wpdb;
        $existsD = $wpdb->get_var( $wpdb->prepare(
                "SELECT meta_value FROM wp_usermeta WHERE user_id = '%s' AND meta_key = 'user_reg_type'" , $uid
            ));
 if($existsD == "userfreelancer"){
                
                $my_post_2 = array(
                    'post_title' => sanitize_text_field($user_info->user_login),
                    'post_status' => 'publish',
                    'post_author' => $uid,
                    'post_type' => 'freelancer',
                    'post_content' => $existsD.'-'.$uid 
                    
                );
$freelancer_id = wp_insert_post($my_post_2);
} elseif($existsD == "useremployer") { 
                
                $my_post = array(
                    'post_title' => sanitize_text_field($user_info->user_login),
                    'post_status' => 'publish',
                    'post_author' => $uid,
                    'post_type' => 'employer',
                    'post_content' => $existsD.'-'.$uid                  
                );
        
                $company_id = wp_insert_post($my_post);
}

Problem is its just takes the first if statement and completely ignores the else if statement.

Thanks in advance. Regards,

1 Answers

Try this

add_action('user_register','registration_funtion', 999);
function registration_funtion($uid){

        global $wpdb;
        $existsD = get_user_meta($uid, 'user_reg_type');

        if($existsD == "userfreelancer"){
                
                $my_post_2 = array(
                    'post_title' => sanitize_text_field($user_info->user_login),
                    'post_status' => 'publish',
                    'post_author' => $uid,
                    'post_type' => 'freelancer',
                    'post_content' => $existsD.'-'.$uid 
                    
                );
                $freelancer_id = wp_insert_post($my_post_2);
        }elseif($existsD == "useremployer") { 
                
                $my_post = array(
                    'post_title' => sanitize_text_field($user_info->user_login),
                    'post_status' => 'publish',
                    'post_author' => $uid,
                    'post_type' => 'employer',
                    'post_content' => $existsD.'-'.$uid                  
                );
        
                $company_id = wp_insert_post($my_post);
        }
Related