Search code examples
wordpresstaxonomy

Automatically add category to post for each user on wordpress site


Sorry for my English. I need your help, if anyone has the time. I would need code to add a category upon new user account and create it in the user's name. thanks a lot for your help

I've searched a bit for information but it's beyond my skills.

add_action('user_register', 'create_taxonomy_name_user'); function create_taxonomy_name_user( $user_id ) { }


Solution

  • Add the function in your active theme functions.php file.

    function create_term_from_username($user_id) {
        // Get the user data
        $user_info = get_userdata($user_id);
    
        //Change if you want term from any other user data
        $username = $user_info->user_login;
    
        //Define in which taxonomy we want to add term 
        $taxonomy = 'category';
    
        // Create a term based on the username
        $term_args = array(
            'slug' => sanitize_title($username), // Sanitize the username to make it suitable for a term slug
        );
    
        // Insert the term and get its ID
        $term_id = wp_insert_term($username, $taxonomy, $term_args);
    
        // Check if the term was created successfully
        if (is_wp_error($term_id)) {
            // Handle error if term creation fails
            error_log('Error creating term for user ' . $username . ': ' . $term_id->get_error_message());
        }
    }
    add_action('user_register', 'create_term_from_username');