Add User Types to WordPress and BuddyPress

Posted by on Aug 8, 2010 in Articles, How-To | 45 comments

There is a new version of this code located at http://cleverness.org/2011/01/27/updated-buddypress-user-roles-code/. Please use that code and leave all comments on that page.

I’ve been working on some more complicated sites than usual at work. One is a social networking site that uses BuddyPress. It’s my first BuddyPress site, so it’s been a learning experience. Additionaly, it was my first WordPress Multi-Site.

One thing I needed to do was allow people to choose a user type at registration. I also needed the user to be assigned a custom Role based on their user type.

I used the Capability Manager Plugin to set the custom roles.

The code is based off How to add custom $usermeta to registration and How to change a users role on the wordpress registration form.

Change the User Type A, usertypea, etc. to whatever you want your user types to be.

Put this in you BuddyPress theme /registration/register.php file:

<label for="signup_type">Account Type:</label>
<select id="signup_type" name="signup_type">
	<option value="usertypea">User Type A</option>
	<option value="usertypeb">User Type B</option>
	<option value="usertypec">User Type C</option>
</select>

Put the following code in your theme’s functions.php:

<?php
/* Add sign-up field to BuddyPress sign-up array*/
function bp_custom_user_signup_field( $usermeta ) {
	$usermeta['signup_type'] = $_POST['signup_type'];

	return $usermeta;
}
add_filter( 'bp_signup_usermeta', 'bp_custom_user_signup_field' );

/* Add field_name from sign-up to usermeta on activation */
function bp_user_activate_field( $signup ) {

	update_usermeta( $signup['user_id'], 'signup_type', $signup['meta']['signup_type'] );

	return $signup;
}
add_filter( 'bp_core_activate_account', 'bp_user_activate_field' );

function synchro_wp_usermeta($user_id, $password, $meta) {
	global $bp, $wpdb;

	$type = $meta[signup_type];

	update_usermeta( $user_id, 'signup_type', $type );

}
add_action( 'wpmu_activate_user', 'synchro_wp_usermeta', 10, 3);

// change user role on registration

function register_role($user_id, $password, $meta) {

	global $bp, $wpdb;

   	$userdata = array();
   	$userdata['ID'] = $user_id;
   	$userdata['role'] = $meta[signup_type];

   	//only allow if user role is my_role

   	if ($userdata['role'] == 'usertypea' || $userdata['role'] == 'usertypeb' || $userdata['role'] == 'usertypec' ){
      	wp_update_user($userdata);
   	}
}

add_action('wpmu_activate_user', 'register_role', 10, 3);
?>

You can use get_user_meta() in your theme files to show different things to different user types.

<?php
global $bp;
if ( get_user_meta($bp->displayed_user->id, 'signup_type') == 'usertypea' ) : ?>
	Put your HTML code here
<?php endif; ?>

You can also read my post on adding BuddyPress profile fields to user types.

45 Comments

  1. Could the selectfield that you put in your registration.php be exchanged with a xprofile-field? I need some filtering for my usertypes – I got bands, fans and clubs – which I want my users to search for?

    • The select field could be replaced with almost anything, as long as you either add the possible values to the functions.php file, or remove the if statement that checks to see if the user type is one you specified.

      • Wish I could do this without any help….
        Would be glad to see an example – if possible.

        Thanks for your help.

        • First of all: happy new year!

          Cindy, I’m still trying to replace the select form by using a xprofile selectbox field. My php and buddypress api knowledge is poor. Is it much work to implement such a field in your “plugin” (which works great for me so far)? Or can anybody else here help me out?

          Greetings,
          Harald

          • Happy new year to you too. I’m going to take a look at my code at the end of the week to see if it can be improved or put into a true plugin. I will try and take a look at the xprofile thing then.

          • cool, thank you. plugin would be a very nice idea. looking forward!

    • I’ve figured out what you need to do to make this work. Remove the code you added from me from the registration file. Add your usertypes as a xprofield field that is in the first group so it shows up on the registration page. Look at the HTML source code and see what the field name is for that xprofile field in the form. It will be something like field_2. Replace all instances of signup_type in the functions.php with that field name. I tried this and it worked.

      • Cindy, you saved my day/week/month/life!

        If someone is also in the need of this function: if you assign xprofile fields to certain groups (http://cleverness.org/2010/10/13/user-types-in-buddypress-assign-xprofile-groups/), then you also have parts of code in a bp-custom.php – there, you also need to replace all instances of signup_type – me, I had to replace 12 instances at all.

        Thank you, you rock!

        • Edit: Instances doesn’t mean “all occurencies”. Will post the code when finished.

  2. displayed_user->id, ‘signup_type’) == ‘usertypea’ ) : ?>
    Put your HTML code here

    ? >

    Can’t get this to work…
    I want to show the Sign Up Type on profile (so I put the code above somewhere in the members/single/member-header.php).
    Any ideas?

    Thanks

    • If you want to display the sign up type, you’ll need to do something like this:

      <?php
      $signup_type = get_user_meta($bp->loggedin_user->id, 'signup_type', true);
      echo $signup_type;
      ?>
      
    • Actually, this is what you want I think. The other code would display whoever is logged in info.

      <?php
      $signup_type = get_user_meta($bp->displayed_user->id, 'signup_type', true);
      echo $signup_type;
      ?>
      
      • Cindy, I can’t manage this feature to work. No matter, where I place the above code-snippet – nothing appears.

        http://www.minemusig.at

        • You may need to add a global bp variable

          <?php
          global $bp;
          $signup_type = get_user_meta($bp->displayed_user->id, 'signup_type', true);
          echo $signup_type;
          ?>
          
          • Thanks, Cindy – that worked!

  3. Cindy, do I need run a multisite-installation, or does this also work on a single wp 3.0.1?

    Thanks for the code!

    • It will work on the single version if you modify the code a little. You have to change wpmu_activate_user to user_register.

      • Thank you, Cindy!

        • After trying for hours, I could not manage to get this running on a single wordpress installation. With multisite enabled it works like a charm!

          Seems the change of “wpmu_activate_user” to “user_register” does not take enough effect on the registration workflow. I took a look on my database: the field signuptype is missing after registration. Also, capabilities were not taken over – just the standard userrole was inserted.

          Any idea, i don’t want and don’t need to run a multisite-installation.

          Thanks in advance

          • Unfortunately, I can’t find an action that would be a suitable replacement. So at the moment I have no idea.

          • What a pity… but I’m glad that I found a way to do it through your solution and it’s working.

            Thank you a thousand times!

          • Hi,

            Would you mind posting your code?

            i’m also kinda stuck, trying to use this code on a normal wordpress website. ๐Ÿ™

  4. Hi!
    This looks like a great plugin! Thanks!

    I’ve installed the plugin and made the adjustments to the code, and when I go to wp-signup.php, I get a blank page. I know this means there’s an error in my code, but I can’t get the error to show.

    Can you help?

    Thanks!

    • If you have access to your PHP error logs, it should show you in there.
      Doublecheck for semi-colon and apostrophes in the right places.

      I can take a quick look sometmie if you email me the files you changed.

  5. Thanks for this, it seems like just what I need but I can’t get it to function correctly. If i’m reading right I should use the Capabilities plugin to create my roles and then use the code above to set the role based on the user input? This is ideal except I keep getting an error when I activate a new user and that user is never assigned to the role they selected.

    The error is:

    Fatal error: Cannot use string offset as an array in C:wampwwwwordpresswp-contentpluginsbuddypressbp-themesbp-defaultfunctions.php on line 262

    I believe it has something to do with the userdata array but im not sure, any ideas?

    • Would you mind sending me your functions.php? You can email it to cindy@cleverness.org. Or at minimum tell me line 262 and the lines before and after it. I’m recovering from a hard drive failure, but I will take a look when I can.

    • Which version are you using as well? I haven’t tested it with the 1.2.6 version that just came out.

    • I’m having the same problem // Am using the latest version of BP

  6. Cindy,
    Thank you for your post!!! I have a question. I would like for specific questions to be answered based on the User-Type. For example during registration (or when filling profile) User Type A would get User Type A Questions, and User B would get only User B specific questions. Is there a plugin or code that you would use to get this to work? I have successfully enabled the User Type Question, just cant understand how to enable specific questions based on roles.

    Thanks!

    • I have this code http://cleverness.org/2010/10/13/user-types-in-buddypress-assign-xprofile-groups/ that allows you to assign specific profile groups to users. That should help you out some.

      • Thanks! I having problems locating the bp-custom.php ( I am new to Buddy Press/Wordpress MU). Should this file be here after installation or is it a file, I would create? Thanks again, I am appreciating this!

        • You will need to create the file. It goes in /wp-content/plugins/.

  7. Greetings Cindy

    first of all thank you very much for this post..

    I’m totally new to BP, but have a good understanding of WP.

    I wish to have different different profile for different kind of ‘members’

    I have explained my goals here

    http://buddypress.org/community/groups/how-to-and-troubleshooting/forum/topic/different-profils-for-different-roles-3/

    I have hard time to find documentation to start with to be able to use the admin to set up profile field set up.. is there a way to ‘re-create’ this page for each profile type or would it be best to have for each profile type a new field group that would be shown on the user profile page if it belongs to that profile group?

    Thank you in advance

    Steffy

    • You could do it either way. If you look at the post I made the other day on assigning xprofile fields to user types, you’ll see the way that displays it on the profile page.

      If you want it on a new page, in your bp-custom.php:

      define('BP_PROFILEA_SLUG', 'profilea');
      
      function profilea_setup_root_component() {
      bp_core_add_root_component( BP_PROFILEA_SLUG );
      }
      add_action( 'plugins_loaded', 'profilea_setup_root_component', 2 );
      

      Made a page in your theme called profilea.php (or whatever you want).

      Copy the code from profile-loop.php, but change part of it to (replace the 2 with your profile group ID):

      <?php if ( function_exists('xprofile_get_profile') ) : ?>
      
      <?php if ( bp_has_profile('profile_group_id=2') ) : ?>
      
      <?php while ( bp_profile_groups() ) : bp_the_profile_group(); ?>
      
      • Greetings Cindy

        First of all thank you very much for your reply.. you have been a light in my darkness..

        I’m totally rookie with BP, so please forgive me if my questions are stupid

        I have made the procedure you wrote

        I put bp-custom.php at the wp-contentplugins

        then I have created profilea.php

        which I have putted at

        wp-contentpluginsbuddypressbp-themesbp-defaultmemberssingleprofile

        it is a copy of profile-loop.php which is based at the same level but with the changes you advised

        when I log back to my admin do I’m supposed to see something changed?
        I have expecting at /wp-admin/admin.php?page=bp-profile-setup something like an option to have profilea page where I could add some fields for that profile type..

        do I have misunderstand something?

        thank you very much in advance

        • by the way I have of course follow what is on the post

          Put this in you BuddyPress theme /registration/register.php file:

          Put the following code in your themeโ€™s functions.php:

          and also follow
          http://cleverness.org/2010/10/13/user-types-in-buddypress-assign-xprofile-groups/

        • First, I want to mention that I realized yesterday that my code for the register.php file was slightly incomplete. Check at the beginning of this post to make sure you have the correct code.

          You’ll want to put the profilea.php at the main level of your theme, where header.php and so on are. This adds a new menu item to the public view, which may or may not be what you want.

          The backend of WordPress will still look the same. You want to go to the BuddyPress menu and the Profile fields page. The different profile sets will be based on groups. You’ll need to create a new group for each set you want.

          • Thank you very much Cindy

            I did the changes you advised, it seems to work

            but I’m localhost and I have no clue how to manually validate a registration via phpmyadmin for example, any idea

            also I assume that I must create the role ‘user-type-a’ via capacity manager, but when I put that name (user-type-a) I got a Error: Failed creating the new role. using a normal word like newrole works

            any idea?

          • It must not like the hyphen. You can replace the user-type-a with a single word in the files. I’ll update the example code.

            Go to the wp_signups database table. There’s a field there called activation key. Then you’ll go to http://localhost/activate/ (or wherever the site url is plus /activate/. Just copy and paste the key.

          • thank you very much for the activate trick.. it fired an error message but got the account validated

            now when I want to create new member on localhost there is no more validation key.. and since if I well understand your code to make it work the validation process must be fired.. I’m a bit stuck there

            but I will investigage

            Thank you again for your most welcomed help

  8. hi,

    thanks for great code!

    one small question. is there any fast way of updating this code, if I want to display specific xprofile groups (in public and edit pages of the BP profile) for specific account type.
    I mean, if during signup user selects ‘User Type A’, in his profile he only see profile group ‘A, B, C’ (if possible, BASE group too).

    many thanks!!!!

    • I’m going to put this info in a new post, since it’s rather large.

  9. Cindy,

    Thanks so much for your response and help! ๐Ÿ˜€

  10. Came across your website while looking for a way to integrate Greg’s High Performance SEO plugin with BuddyPress.

    I’m very excited to see your Base WordPress theme and it’s inclusion of support for this SEO plugin. Do you have any pointers for trying to get Greg’s plugin to work with a BuddyPress theme?

    I have some specific code that I’m looking to implement ghpseo_output(‘main_title’); into (gotta start somewhere), but I figure I can’t copy and paste code into the comment section here.

    Any tips would be greatly appreciated – and there’s not much information about this that I have found so it could make a good future post if you were so inclined. Again, thanks!

    • If you’re looking to show the main_title on regular WordPress pages and the BuddyPress titles on BuddyPress pages, you can use this:

      <title>
      <?php
      if (function_exists('ghpseo_output') && ghpseo_output('main_title', false) != '')
          ghpseo_output('main_title');
      else bp_page_title();
      ?>
      </title>
      

      Hope that helps some.

Trackbacks/Pingbacks

  1. Updated BuddyPress User Roles Code - [...] post on adding user types to WordPress and Buddypress has been very [...]

Leave a Reply

Your email address will not be published. Required fields are marked *