Samuel Elh Blog

WordPress, bbPress, BuddyPress, JavaScript tutorials and snippets

Tag: topics

Add custom fields to bbpress profile

bbPress is great free and open source plugin for the implementation of forums and user profiles and discussion on a WordPress blog/website or a multisite. It comes with great features out of the box, using WordPress API to build neat and SEO-friendly forums, with many other features.

The many advantages of bbPress is, it is easy to use, and fully extensible for the sake of bringing more features and tools. Today, we’ll go through some easy steps to add additional custom fields to bbPress profile, and displaying them on the user profile, as well as add fields for those in the bbPress profile edit, and handle processing everything.

Add custom fields to bbPress profile edit form

There are so many HTML5 field types you can add as custom fields, from checkbox to Google Maps coordinates, but for the sake of simplicity we’ll keep it simple as possible and go for an example of a simple drop down menu for letting users to select their own cities.

Finding the perfect section in profile edit to parse custom fields:

If you take a look at templates/default/bbpress/form-user-edit.php file located in the bbPress plugin folder, that is actually the code that makes up the profile edit page template. You’ll notice many do_action callback lines, that is the WordPress API used to let us extend the area and add other fields. The point is, I’ll be hooking to a specific hook, but you should always look at that file to find the appropriate hook name to use for you case, so as to parse fields in the appropriate section possible.

Here’s a hook list that might be at your help (it is not a complete one, I focused on the hooks occurring after each section fields since we’re after adding extra custom fields):

  • bbp_user_edit_after_name: Will add fields after the “Name” section in bbPress edit profile
  • bbp_user_edit_after_contact: Will parse fields after “Contact Info” section fields.
  • bbp_user_edit_after_about: Will add fields after “About Yourself” section.
  • bbp_user_edit_after_account: Will add fields after “Account” section.
  •  bbp_user_edit_after_role: Will add fields “User Role” section fields.

You may notice all the hooks point to “after” in the name, there’s also “before” hooks to parse fields before the existing ones, and you can use them as well, I just felt lazy letting them in!

You can and may also register a custom section for your data, either before everything (bbp_user_edit_before) or after (bbp_user_edit_after), and use the same HTML section containers as bbPress to get the matching style, or style your custom section accordingly.

Parse custom field into bbPress profile edit:

Once you have the appropriate action hook, hook it to function callback that prints our custom fields and embeds them. Like I mentioned earlier, I am going to add a drop-down city select for users, so the best section for the case is under “Contact Info”:

add_action( "bbp_user_edit_after_contact", "se_add_city_field" );

function se_add_city_field() {
    // a random selection of cities
    $cities = array( "Seoul", "Mexico City", "Amsterdam", "Mumbai", "Agadir", "Egypt" );
    ?>
    <div>
        <label for="city"><?php _e( 'City', 'my-domain' ); ?></label>
        <select name="city" id="city">
            <option value="">Select City</option>
            <?php foreach ( $cities as $city ) : ?>
                <option><?php echo esc_attr( $city ); ?></option>
            <?php endforeach; ?>
        </select>
    </div>
    <?php
}

Now you’ll probably notice there’s an extra field for city that has just been appended to bbPress profile edit form, below contact info fields:

city field added bbpress

That’s great. Now we are done with the step of appending the field to the edit profile form. Guess next up is processing this field upon user saving their profile and save the right data to the database? carry on.

Process custom fields while saving bbPress profile

This is quite a simple step as bbPress provides hooks to hook into profile saving.

We’ll check if the city field is set and if the city is selected, then save this city into a custom user meta (in the database), otherwise, delete the user meta for city to let the user unset their city by anytime:

// when updating our profile
add_action( "personal_options_update", "se_save_city_value" );
// when updating other users' profiles
add_action( "edit_user_profile_update", "se_save_city_value" );

function se_save_city_value( $user_id ) {
    // exclude profile.php/user-edit update
    if ( is_admin() ) return;
    // update preference
    if ( isset( $_POST['city'] ) && $_POST['city'] ) {
        return update_user_meta( $user_id, "se_city", sanitize_text_field( $_POST['city'] ) );
    } else {
        return delete_user_meta( $user_id, "se_city" );
    }
}

I hooked into two action hooks this time because I noticed bbPress fires the first one only when a user is updating their own profile, while the second one runs when updating others profiles, as any admin can edit other users which makes sense.

Now running the first test, I am selecting a city and saving profile, the city has been saved in a custom user meta with key se_city which we can use later to embed the selected city into user profile, and also to check the selected city in the profile edit screen in the drop-down menu for city:

function se_add_city_field() {
    // a random selection of cities
    $cities = array( "Seoul", "Mexico City", "Amsterdam", "Mumbai", "Agadir", "Egypt" );
    // selected city, if any
    $user_city = bbp_get_displayed_user_field('se_city');
    ?>
    <div>
        <label for="city"><?php _e( 'City', 'my-domain' ); ?></label>
        <select name="city" id="city">
            <option value="">Select City</option>
            <?php foreach ( $cities as $city ) : ?>
                <option <?php selected($user_city,$city); ?>><?php echo esc_attr( $city ); ?></option>
            <?php endforeach; ?>
        </select>
    </div>
    <?php
}

I went back to edit the function se_add_city_field() which embeds the country drop-down in the profile edit screen. To get any kind of user meta while in the bbPress profile, use

bbp_get_displayed_user_field( $meta_key )

where $meta_key is the custom user meta key, let it be ID to get the displayed user ID, or se_city to get the city we just saved (in the database, not in the real world).

I also used selected() to auto select the option that corresponds to the selected city in the drop-down. You can use checked() when dealing with radio buttons or check-boxes, or PHP to add attributes and HTML properly. It is always a neat idea to use the helper functions provided by WordPress for better performance, security and all.

Display custom fields in bbPress user profile

After all, we can say we have added custom fields to bbPress profiles and users can now edit their profiles to input their correct details. We can now embed these custom fields anywhere, let it be in their bbPress profile, in a custom bbPress profile tab, below topic or reply author details for this user, etc, etc.

For the sake of simplicity for this tutorial I am going to parse the city field in the bbPress user profile, and in the topic/reply after author details.

After bbPress user profile:

// add city after user profile details
add_action( "bbp_template_after_user_profile", "se_embed_city_profile" );

function se_embed_city_profile() {
    // selected city, if any
    $user_city = bbp_get_displayed_user_field('se_city');
    // making sure user has set their city first
    if ( !trim( $user_city ) ) return;
    // all good
    return printf(
        '<p>%s is based on <strong>%s</strong></p>',
        esc_attr( bbp_get_displayed_user_field('nickname') ),
        esc_attr( $user_city )
    );
}

I am using the bbPress function bbp_get_displayed_user_field() to get the nickname and all, because it already loads all this users’s meta which makes sense for great performance, and I am taking advantage of that, while you can use other methods to get the displayed user data, such as ID with bbp_get_displayed_user_id(), display name with

get_userdata( bbp_get_displayed_user_id() )->display_name

, etc..

Now here’s a preview of the city field displayed into my bbPress profile on my local installation:

city field bbpress profile

Great! We promised to embed the city below bbPress topics and replies as well, right after the author details, so here we go:

// add city after topic/reply author details
add_action( "bbp_theme_after_reply_author_details", "se_embed_city_forums" );

function se_embed_city_forums() {
    // topic/reply author
    $user_id = bbp_get_reply_author_id();
    // selected city, if any
    $user_city = get_user_meta( $user_id, 'se_city', true );
    // making sure user has set their city first
    if ( !trim( $user_city ) ) return;
    // all good
    return printf(
        '<p>%s is based on <strong>%s</strong></p>',
        esc_attr( bbp_get_displayed_user_field('nickname') ),
        esc_attr( $user_city )
    );
}

This time we use

bbp_get_reply_author_id()

function to get the correct user ID for the topic/reply author, and

get_user_meta()

to get the custom meta saved as city.

Here’s a preview:

city field bbpress topic-reply

Full Tutorial Code

Fin

That is it for this tutorial. I hope that helps. Feel free to discuss below. Thank You!

bbPress favorites total count by user ID

In this quick tip, we will try to get the total bbPress favorites made for all topics by a specific user, counting total favorites received on every topic this user has posted on the forums.

As if you don’t know, there’s this function bbp_get_topic_favoriters( int $post_ID ) that you can call to get an array of users who have favorite’d this topic we are specifying its POST ID in the first param. That is what we will use to count total bbPress favorites on all topics as we query topics by user ID who is the author of these topics.

We will use WordPress API get_posts to list all topics of the user we’re after.

function se_bbp_total_favorites_by_user( $user_id ) {
	$args = array( 'post_type' => array('topic'), 'author' => $user_id, 'posts_per_page' => -1 );
	$posts = get_posts( $args );
	$count = 0;

	if ( !empty( $posts ) ) {
		foreach ( $posts as $post ) {
			$count += count( bbp_get_topic_favoriters( $post->ID ) );
		}
	}

	return (int) $count;
}

Good, now simply call se_bbp_total_favorites_by_user( 1 ) with the user ID instead of 1 and it should be working perfect.

Caching bbPress favorites:

Please note that you should not always make query to the posts while you can do it in the first time and cache data for a later use with custom expiration interval. Caching is always the best tool out there to minimize the load time, and reduce memory and server ressource usage, and because this is simple enough, let’s just use WordPress transients for non-persistent caching, and set the timeout to a week or 2 days (DAY_IN_SECONDS * 2) or just flush every time a topic gets favorited (I don’t know how to hook into this, guess you’ll have to look into the core files for a custom hook)

Getting All Favorited Topics By User:

I have looked around the usermeta table in PMA of a local install, and I found out that all topics favorites by a user are saved in a custom user meta with the name of wp__bbp_favorites, saved in a comma-separated format. This can be used to list all topics that this user has favorited, as we’ll just look for that meta, explode the commas and we’re all set with the topics IDs.

function se_bbp_favorites_by_user( $user_id ) {
	$meta = get_user_meta( $user_id, "wp__bbp_favorites", 1 );
	if ( $meta ) {
		$meta = explode( ",", $meta );
		$meta = array_filter( $meta );
		if ( !empty( $meta ) ) {
			foreach ( $meta as $i => $topic_id ) {
				$meta[$i] = (int) $topic_id;
				/*
				* you might want to check if this post exists
				* or instead of attaching post ID only, make it post data
				* as $meta[$i] = get_post( $topic_id );
				*/
			}
		}
	} else return array();
	return $meta;
}

For this one, no need to worry about the caching (as long as you keep it simple as is) because by default, WordPress caches the user meta and loads it in memory; the cache will automatically be flushed when the user meta is updated (cool stuff right? WordPress!)

© 2017 Samuel Elh - Powered by WordPress, DigitalOcean & NameCheap

Theme by Anders NorenUp ↑

Subscribe to our mailing list

Sign up to receive updates about WordPress, free and premium plugins and themes in general and tips and tricks

* indicates required