Samuel Elh Blog

WordPress, bbPress, BuddyPress, JavaScript tutorials and snippets

Tag: bbpress

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" );
        <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; ?>

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');
        <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; ?>

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


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


to get the custom meta saved as city.

Here’s a preview:

city field bbpress topic-reply

Full Tutorial Code


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!)

bbPress Messages – Send automatic welcome messages to new users

bbPress Messages – customizing and extending

Send automatic greeting and welcome messages to new users

In this quick tutorial we are going to talk about how to enable custom messages sent automatically to new user upon a successful registration on our WordPress blog or website.

Required plugins

For this process, you’re going to need:

  • bbPress, the parent plugin of bbPress Messages, for powering forums and communities
  • bbPress Messages: PRO ( v. 0.2.4 or greater), or lite ( v. 0.2.3 or greater ).

That’s all, and no, no BuddyPress is needed or involved.

Extending user registration system

We will be hooking into user_register, which provides us with a user ID for the currently registered user, which we will use to email the user a greeting and welcoming custom message of our own.

Make sure to provide a sender ID, and this is totally required, for the sake of simplicity I made it 1, which will be the first user on your blog and the admin. To find our your user ID, go to users, find your account, and click edit. Now in the address bar there will be something like ?user_id=ID_HERE . That’s the ID you should insert in the sender in follows-code.


Using BBP_messages_message::sender method

This method will allow us to insert the message. It takes 4 parameters, 3 required and one optional:

  • $user_id: (int) the recipient which we will direct the message to.
  • $message: (string) the custom message we are sending.
  • $sender: (int) the message sender user ID, which the user will be able to reply to (if possible) later upon login.
  • $notify(bool) choose whether to notify this user by email about this message or not. It defaults to true, but you can set it to false to not email.

The coding:

Add the following code, to your child theme’s functions file or with a custom plugin, and make sure to make necessary edits such as customizing the message and inserting the message sender ID.

add_action("user_register", function( $user_id ) { 
	if ( !class_exists('BBP_messages_message') ) return; // bbPress messages is not there

	$sender = 1; // admin. Please provide a valid user ID
	$message = sprintf(
		"Greetings, %s!\n\nThis is an automated message, sent to greet and thank you for signing up for a membership on our website.\n\nSee you online,\n%s &mdash; %s.",
		get_userdata( $user_id )->display_name,
		get_userdata( $sender )->display_name,
		get_bloginfo( "name" )
	); // message format

	return BBP_messages_message::sender( $user_id, $message, $sender );

That’s it. Hope this tutorial helps you greet and welcome your newly registered bbPress users, and point them to use the messaging functionality or provide instructions and so forth..

If you had any issues, please post in the plugin support forum provided provided by the author.

Link WordPress comment author to bbPress profile

In this quick tutorial, we will filter the WordPress comment author link URL and point to bbPress profile of this author as long as the comment was made by a verified user of your blog.

We can hook into get_comment_author_link for filtering the comment author link, and to get the bbPress profile link of a given user, you can use

bbp_user_profile_url( $user_id )

for this purpose for which you specify a user ID in the first parameter.

The code:

Add the following code to your child theme’s functions file or with a custom plugin:

add_filter('get_comment_author_link', function( $link ) {

	if ( !function_exists('bbp_user_profile_url') )
		return $link;

    global $comment;
    if ( !empty( $comment->user_id ) && !empty( get_userdata( $comment->user_id )->ID ) ) {

   		$link = sprintf(
   			'<a href="%s" rel="external nofollow" class="url">%s</a>',
   			bbp_get_user_profile_url( $comment->user_id ),
   			strip_tags( $link )


    return $link;

To make the avatar clickable as well, see how to add Link to WordPress Comment Avatar

Add Link to WordPress Comment Avatar

In this quick snippet of coding tutorial, we learn about adding an anchor link to WordPress comment avatar.

Link WordPress Comment Avatar

By default, if a user has left a comment on your WordPress blog through a post comment form, they can specify a link to their website, which will be assigned as anchor to the name they specified and displayed within the comments loop, and WordPress does not make this link added to the avatars.

Filtering get_avatar:

Simple work-around for achieving this is by filtering entire get_avatar output, which we will concentrate to apply this only when the queried avatar (gravatar) is used for comments, and this can be achieved by checking the second parameter provided while hooking into get_avatar, if it is a comment identifier, while it can be a user ID, email address or something else.

The coding:

Add the following code to your child theme’s functions file or with a custom plugin:

  * PHP < 5.3 ? use a custom function instead of the anonymous callback

add_filter('get_avatar', function( $avatar, $indent ) {

	  * check if the current queried avatar is for comments

	if ( !empty( $indent->comment_ID ) ) { // now that's a comment avatar

		  * Check if the comment poster has left a link
		  * You can link somewhere else regardless of link availability
		  * by commenting out the if statement lines and specifying a $url
		  * in the sprintf 2nd param, e.g link to bbPress, BuddyPress, author
		  * archives, etc..

		if ( "" < ( $url = get_comment_author_url( $indent->comment_ID ) ) ) {
			$avatar = sprintf(
	   			'<a href="%s" rel="external nofollow" class="url">%s</a>',


	return $avatar;

}, 10, 2);

That should make the avatar clickable in the comments section and ONLY if the comment author has left and specified a URL in the website comment form field while submitting.

Filter avatar link:

You can link to something else, such as bbPress profile

bbp_get_user_profile_url( $ident->user_id )

or BuddyPress profile

bp_core_get_user_domain( $ident->user_id )

or even to the author archives of this user ( and to know if the comment author is a verified registered user, just check if $ident->user_id is not empty ):

get_author_posts_url( $ident->user_id )

This should always work as long as you’re pulling the comment avatar by the comment ID in your comments output callback function, that if you are overriding the default WordPress’s comments callback.

How to add a captcha to bbPress Messages plugin

Hello World,

So in this basic tutorial I am going to talk about how you can implement a spam quiz (know as Captcha) in your WordPress installation.

From the title, you’ll be required to use bbPress Messages v. 0.2.2 or greater, for the lite version I am going to make an update very shortly and you’ll be able to implement and complete this process on your lite plugin as well.

Using reCaptcha for bbPress Messages WordPress Plugin addon:

google reCaptcha bbPress messages

I have spent couple hours making a simple plugin to add and enable Google reCaptcha anti-spam in your bbPress Messages plugin. It is available for download on Github, make sure to check

Working your own script:

First things first, let’s talk a little about captchas:

A Captcha can be used to ignore and kill some (if not all) robot requests to your scripts. Now here with WordPress, it’s a common issue that you can have spam users signup and sign in to your website, and from there make request calls which are limited to logged in users now that they are logged in.

Beating these malware bots can be a real trouble, especially when you are on shared hosting or run server with limited ressources. Spam can eat up your bandwidth, and get you in trouble with your host and make you pay more money for the ressources.

Implementing a Captcha in bbPress Messages:

bbPress Messages WordPress plugin is very easy to extend, you can just read the core files to find any hook you need then hook into it. That is what we are going to do to add a spam check tool for specific user roles.

bbPress Messages already uses WordPress nonces which can be handy most of the time.

You can use image Captchas, test written on image, but those could be beaten up easily nowadays since there are hundreds or anti-captcha scripts and APIs and OCR providers, that could not work most of the time..

In the following example we will be using a simple test, where we till our user to calculate something and do the maths.

“What’s 9+10?” – let’s try to use the word plus instead of symbol, perhaps bots will get workarounds to solve that one but when providing words and hints you are causing them more failure to solve the test.

User roles:

If you want to show the spam test to only one or specific roles, add or remove those roles in the following function in the 11th line:

Good. Now we know when to add the spam test and validate the answer provided by the user before sending a message.

Embed fields into form:

Now we will add the fields for the spam check into the conversation input form. Remember, you can go for any quiz you want, just name it and validate the client provided solution (we’ll talk about this later) as you go.

We will hook into ‘bbpm_conversation_form_additional_fields’ tag which puts fields within the form:

Now we can see that the field is added to the form:

bbpress messages spam check form preview

Awesome! now let’s talk about the validation.

Validating the solution:

This is the last part where we will be verifying the form data to get our spam test user input. We’ll then see if the answer is correct or not, then allow sending if everything’s good.

I am not going to explain the code line by line because it depends on the type of quiz you implement. For this tutorial the user input is stored in an input named


and the form has a POST method so the way of getting the value is through


and there we validate the answer.

We’ll hook into ‘bbpm_bail_sending_message’ this time to filter whether to bail sending the current message or not. When the captcha answer is wrong then we bail:

As we bail sending, an error will be added to the user interface in the front-end telling the user that something went wrong.. That means the spam quiz was not completed successfully..

To conclude, I have put the full code into a Github gist and you can add it to your child theme’s functions file in order for this process to work, after making your modifications:

I have fully tested it and it works great on my installations. If anything went wrong or you need help with your code, feel free to discuss below ( no wonder how much spam would this topic attract ;~) )

How to enable hashtags in WordPress post/page content

How to enable hashtags in WordPress post/page content

Hello everyone,

So basically as the title says, in this tutorial we will be up to enabling hashtags in WordPress to be automatically detected in our post or page content and automatically make those hashes link to our site or an external site such as Twitter or Facebook, with the hashtags set within the URL.

The aim of this tutorial is enabling this functionality quickly without a WordPress plugin or additional coding struggle.

We will be filtering the post content to detect whether there are hashes in the content or whether not, if hashtags were found, then, let’s turn them into links! deal? Cool.

But, while we do this, we know that sometimes in the content, there are HTML entities beginning with hashes #, and also in-page hash links or what we call fake links a href="#div" so at this point we will try to ignore those elements.

So the first thing is trying not to parse the HTML fake links (sorry I had no way of doing this in the preg_replace function so I came up with another workaround trick):

$content = str_replace( array('href="#', 'href=\'#', 'href=#'), array('href="{nulled_hash}', 'href=\'{nulled_hash}', 'href={nulled_hash}'), $content );

So now that we have temporary removed hashes from the links, and we will add them back later after the parsing of hashtags is done:

$content = preg_replace('/#(\w+)/', '<a href="$1/">#$1</a>', html_entity_decode($content));


Next thing is getting back the fake links their hashes, you may have noticed that we already decoded HTML entities and since decoded, those entities won’t be returning any hashes.

$content = str_replace( array( '{nulled_hash}', '{ignore_hash}' ), '#', &amp;nbsp;$content );

Wrapping the whole code in a function applied to a filter of the_content :

add_filter('the_content', function() {

 $content = str_replace( array('href="#', 'href=\'#', 'href=#'), array('href="{nulled_hash}', 'href=\'{nulled_hash}', 'href={nulled_hash}'), $content );
 $content = preg_replace('/#(\w+)/', '<a href="$1/">#$1</a>', html_entity_decode($content));
 $content = str_replace( array( '{nulled_hash}', '{ignore_hash}' ), '#', $content );
 return $content;


Now saving that code in your child theme’s functions file would get the hashtags parsed immediately.

You can add further filters, such as the_title for posts title, comment_text for the comment body text, widget_text and widget_title for widgets, bp_get_activity_content_body for BuddyPress activity streams etc, etc.

Edit: I have recently submitted a plugin to repository and it is under review. It is named WP Hashtags you should use it with ease to add functionality to your WordPress, bbPress and BuddyPress content parsing hashtags. It is actually available on Github

How to filter bbPress forum and topic freshness links

How to filter bbPress forum and topic freshness links


In this tutorial we will try to filter bbPress forum and topic freshness links to display the kind of stuff that we are after.

Before filtering bbPress forum and topic freshness links

Before applying filters

After filtering bbPress forum and topic freshness links

After applying filters

In the above screenshot, all I wanted to achieve was to remove multiple time difference quantities and have only one, so for example rather than saying 2 months, 1 hour, 2 minutes, 1 second ago, we simply say 2 months ago. And in the filter I remove the portion of the freshness link text which is after the first found comma (,):

// add the following code to your child theme's functions file
add_filter('bbp_get_forum_freshness_link', 'my_filters_for_freshness_link');
add_filter('bbp_get_topic_freshness_link', 'my_filters_for_freshness_link');
function my_filters_for_freshness_link($anchor) {
  $return = strpos($anchor, ',') ? substr($anchor, 0, strpos($anchor, ",")) . ' ago' : false; 
  $return .= strpos($return, 'a href') ? '</a>' : '';
  return $return ? $return : $anchor;

You can also display something else, since we can get the forum or topic ID, we can get the post time and date and show the simple date instead of time difference for instance, etc, etc.

add_filter('bbp_get_forum_freshness_link', 'my_filters_for_freshness_link', 10, 2);
add_filter('bbp_get_topic_freshness_link', 'my_filters_for_freshness_link', 10, 2);
function my_filters_for_freshness_link($anchor, $post_id) {
  $post_date = get_post( $post_id )->post_date;
  return $post_date;

Just play around with it, show your custom content, or whatever, and stay away from syntax errors or getting your pretty forums messed up!

How to enable visual editor in bbPress topic and reply forms

How to enable visual editor in bbPress topic and reply forms

As per the codex, you can enable visual editor in the topic and reply forms by adding the following code to your actual theme’s functions.php file or with a custom plugin. And please consider using child themes always:

add_filter( 'bbp_after_get_the_content_parse_args', function( $args = array() ) {
 $args['tinymce'] = true;
 return $args;

Please consider reading more about this filter in bbPress codex.

© 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