BuddyPress 开发者手册

BuddyPress 开发者手册,介绍组件与扩展开发。

Building a custom BuddyPress component

Located inside the /bp-core/classes directory, the BP_Component class can be used as the parent of your custom component's class to organize it. BuddyPress components are registered into the main buddypress() instance using their ID: a unique string which is generally the same as your component default slug. This registration step is hooked to the bp_setup_components action. Below is an example of how you can register your component in BuddyPress.

function register_custom_component() {
	/*
	 * BP_Custom_Component is the class of your component.
	 * You'll discover in the rest of this documentation resource how you
	 * can build this class.
	 */ 
	buddypress()->custom = new BP_Custom_Component();
}
add_action( 'bp_setup_components', 'register_custom_component' );

You can use the third argument ($priority the priority argument) of the add_action() function to choose when your component will be inited as long as it is after 1 to be sure required components have been inited, in the above example custom is hooked at default priority ie: 10. Here's the initiation order of built-in BuddyPress components:

Building your component’s class

It’s a WordPress good practice to put the code of your class into a file having a class- prefix followed by your class name where caps are replaced by their corresponding lower case value and underscores by dashes. As our custom component's class is named BP_Custom_Component, we are putting its code inside a class-bp-custom-component.php file. Let's built it making sure you will inherit from the BP_Component parent class using the extends keyword.

class BP_Custom_Component extends BP_Component {
	/*
	 * The properties and methods of for your component's class.
	 */ 
}

Adding the constructor of your class

This is where you are using the BP_Component::start() method to inform about some of your component's globals such as your component ID, your component name, the path from where additional files should be included and additional parameters such as the position for your menu under the WP Toolbar's "My Account menu", your component optional features and the string to be used as the query argument in component search URLs.

class BP_Custom_Component extends BP_Component {
	/**
	 * Your component's constructor.
	 */
	public function __construct() {
		parent::start(
			// Your component ID.
			'custom',

			// The raw name for your component. Do not use translatable strings here.
			'Custom component',

			/*
			 * The path from where additional files should be included.
			 * 
			 * FYI: this class is inside an `/inc` subdirectory of your add-on directory.
			 * 
			 * Below is a typical relative path for it:
			 * `/wp-content/plugins/bp-custom/inc/classes/class-bp-custom-component.php
			 */ 
			plugin_dir_path( dirname( __FILE__ ) ),

			// Additional parameters.
			array(
				'adminbar_myaccount_order' => 100,
				'features'                 => array( 'feature-one', 'feature-two' ),
				'search_query_arg'         => 'custom-component-search',
			)
		);
	}
}

Setting up your component global variables

Your component's class can include a setup_globals() method to define BP specific globals or custom ones. If you do add this method to your class, it will override the BP_Component::setup_globals(). In this case, to be sure to reference your component inside the BuddyPress loaded_components queue and your component's BP specific globals, don't forget to call parent::setup_globals( $bp_globals ); inside your method.

class BP_Custom_Component extends BP_Component {
	/**
	 * A custom global for your component only.
	 * 
	 * @var boolean
	 */
	public $custom_global = false;

	public function __construct() { /** Your component's constructor code. */ }

	/**
	 * Setup BP Specific globals and custom ones.
	 * 
	 * @since BuddyPress 1.5.0
	 * 
	 * @param array $bp_globals {
	 *     All values are optional.
	 *     @type string   $slug                  The portion of URL to use for a member's page about your component.
	 *                                           Default: the component's ID.
	 *     @type string   $root_slug             The portion of URL to use for your component's directory page.
	 *     @type boolean  $has_directory         Whether your component is using a directory page or not.
	 *     @type array    $rewrite_ids           Your components rewrite IDs.
	 *     @type string   $directory_title       The title of your component's directory page.
	 *     @type string   $search_string         The placeholder text in the component directory search box.
	 *                                           Eg: 'Search Custom objects...'.
	 *     @type callable $notification_callback The callable function that formats the component's notifications.
	 *     @type array    $global_tables         An array of database table names.
	 *     @type array    $meta_tables           An array of metadata table names.
	 *     @type array    $block_globals         An array of globalized data for your component's Blocks.
	 * }
	 */
	public function setup_globals( $bp_globals = array() ) {
		$bp_globals = array(
			'slug'          => 'custom-slug',
			'has_directory' => false,
		);

		// BP Specific globals.
		parent::setup_globals( $bp_globals );

		// Your component's globals (if needed).
		$this->custom_global = true;
	}
}

Including files

Depending on how you will organize your add-on, you may need to include some other PHP files. The includes() method of your component can be used to do so. You'll simply need to call parent::includes( $files ) where $files is the list of the filenames you need to load.

class BP_Custom_AddOn_Component extends BP_Component {
	public function __construct() { /** Your component's constructor code. */ }
	public function setup_globals( $bp_globals = array() ) { /** Your component's code to set custom/BP globals. */ }

	/**
	 * Include your component's required files.
	 * 
	 * @since BuddyPress 1.5.0
	 *
	 * @param array $files An array of file names located into `$this->path`.
	 *                     NB: `$this->path` in this example is `/wp-content/plugins/bp-custom/inc`
	 */
	public function includes( $files = array() ) {
		parent::includes(
			array(
				'functions.php',
			)
		);
	}
}

Even if you can directly include your files without overriding/calling from your component's method BP_Component::includes( $files ), as BuddyPress triggers a dynamic hook at the end of this method, it's a good practice to use it!

Adding your custom menu items to the single Member's navigation

Here's a method with a more concrete result! Thanks to it, you will be able to create specific pages for your component inside the single Member’s area.

Single Member’s area

To get this result, you need to override the BP_Component::setup_nav() method from your component’s to define 2 arrays before sending them to parent::setup_nav( $main_nav, $sub_nav ) as shown below.

class BP_Custom_AddOn_Component extends BP_Component {
	public function __construct() { /** Your component’s constructor code. */ }
	public function setup_globals( $bp_globals = array() ) { /** Your component’s code to set custom/BP globals. */ }
	public function includes( $files = array() ) { /** Your component’s code to include required files. */ }

	/**
	 * Add your custom menu items to the single Member's navigation.
	 *
	 * @since BuddyPress 1.5.0
	 *
	 * @param array $main_nav Associative array
	 * @param array $sub_nav  Optional. Multidimensional Associative array.
	 */
	public function setup_nav( $main_nav = array(), $sub_nav = array() ) {
		$parent_url = bp_get_members_component_link( $this->id );

		if ( $parent_url ) {
			// Member main navigation.
			$main_nav = array(
				'name'                => $this->name,
				'slug'                => $this->slug,
				'position'            => 100,
				'screen_function'     => 'bp_custom_add_on_screen_callback',
				'default_subnav_slug' => 'default-subnav-slug',
				'item_css_id'         => $this->id,
			);

			// Member sub navigation.
			$sub_nav = array(
				array(
					'name'            => __( 'Default sub nav name', 'custom-text-domain' ),
					'slug'            => 'default-subnav-slug',
					'parent_slug'     => $this->slug,
					'parent_url'      => $parent_url,
					'position'        => 10,
					'screen_function' => 'bp_custom_add_on_screen_callback',
					'item_css_id'     => 'default-subnav-' . $this->id,
				),
				array(
					'name'            => __( 'Other sub nav name', 'custom-text-domain' ),
					'slug'            => 'other-subnav-slug',
					'parent_slug'     => $this->slug,
					'parent_url'      => $parent_url,
					'position'        => 20,
					'screen_function' => 'bp_custom_add_on_screen_callback',
					'item_css_id'     => 'other-subnav-' . $this->id,
				),
			);
		}

		parent::setup_nav( $main_nav, $sub_nav );
	}
}

BP_Component::setup_nav() will use these two arrays to generate the single Member’s navigation items for your components using bp_core_new_nav_item() for your main navigation item and bp_core_new_subnav_item() for your sub navigation items. The $parent_url attribute of your sub navigation multidimensional array is only needed for BuddyPress versions that are lower than 12.0.0. The $screen_function attribute is required for both arrays as the callback function you choose will be triggered to load the BuddyPress single member’s template needed by your Add-on. Most of the time, this callback function should include bp_core_load_template( 'members/single/home' ); to do so.

To have the "It works!" content on the component’s single member displayed page, here's the code that was used inside the functions.php page that was included previously:

function bp_custom_add_on_screen_displayed() {
	echo 'It works!';
}

/**
 * The screen function referenced as the `$screen_function` of your
 * navigation arrays. Of course you can use different screen functions
 * for each of your sub navigation items.
 */ 
function bp_custom_add_on_screen_callback() {
	bp_core_load_template( 'members/single/home' );

	add_action( 'bp_template_content', 'bp_custom_add_on_screen_displayed' );
}

By default, unless you filtered how BuddyPress is loading templates, the buddypress/members/single/plugins.php of the active BP Template Pack or of your active standalone BuddyPress theme will be loaded to display your Add-on’s content.

Making sure the URL of your component’s single member pages can be customized.

Using BP_Component::setup_nav() to generate your component’s single member navigation will work for any BuddyPress versions (well actually those which are >= 1.5.0).

BuddyPress 12.0.0 introduced a major change about how URL requests are parsed and analyzed to serve BuddyPress content. One of the benefits of this change is the ability for the Site Owner to customize every BuddyPress URLs from the URLs tab of the BuddyPress settings you can reach from your WordPress Dashboard.

Although BuddyPress built-in components automatically enjoy URL slugs customization, your custom component won't unless you override a specific method which is only available since BuddyPress 12.0.0: BP_Component::register_nav(). When you override this method you don't need to override BP_Component::setup_nav() anymore. Although BP_Component::register_nav() accepts the same arguments than BP_Component::setup_nav(), it's slightly different as it's fired very early into the BuddyPress loading process. For this reason, if you were familiar with restricting access to some navigation items using functions like bp_core_can_edit_settings() or bp_is_my_profile() into the $show_for_displayed_user argument of your main navigation array or into the $user_has_access argument of your sub navigation multidimensional array, you will now need to reference them as callbacks into the $user_has_access_callback argument of your main navigation array or your sub navigation multidimensional array. Once BuddyPress URL globals will be set the BP_Component::setup_nav() will call these callbacks to eventually restrict access to your component’s single member pages.

class BP_Custom_AddOn_Component extends BP_Component {
	public function __construct() { /** Your component’s constructor code. */ }
	public function setup_globals( $bp_globals = array() ) { /** Your component’s code to set custom/BP globals. */ }
	public function includes( $files = array() ) { /** Your component’s code to include required files. */ }

	/**
	 * Register your custom menu items into the single Member's navigation.
	 *
	 * @since 12.0.0
	 *
	 * @param array $main_nav Associative array
	 * @param array $sub_nav  Optional. Multidimensional Associative array.
	 */
	public function register_nav( $main_nav = array(), $sub_nav = array() ) {
		parent::register_nav(
			array(
				'name'                => $this->name,
				'slug'                => $this->slug,
				'position'            => 100,
				'screen_function'     => 'bp_custom_add_on_screen_callback',
				'default_subnav_slug' => 'default-subnav-slug',
				'item_css_id'         => $this->id,
			),
			array(
				array(
					'name'            => __( 'Default sub nav name', 'custom-text-domain' ),
					'slug'            => 'default-subnav-slug',
					'parent_slug'     => $this->slug,
					'position'        => 10,
					'screen_function' => 'bp_custom_add_on_screen_callback',
					'item_css_id'     => 'default-subnav-' . $this->id,
				),
				array(
					'name'                     => __( 'Other sub nav name', 'custom-text-domain' ),
					'slug'                     => 'other-subnav-slug',
					'parent_slug'              => $this->slug,
					'position'                 => 20,
					'screen_function'          => 'bp_custom_add_on_screen_callback',
					'item_css_id'              => 'other-subnav-' . $this->id,

					// Let's restrict this page to members viewing their own profile.
					'user_has_access_callback' => 'bp_is_my_profile',
				),
			)
		);
	}
}

In the above code, we are only overriding BP_Component::register_nav() to generate the custom component’s single member navigation items and to restrict the access of the "Other sub nav name" sub item we are using the 'bp_is_my_profile' callback inside the $user_has_access_callback argument of the corresponding entry of the multidimensional array. If you go to the URLs tab of the BuddyPress settings of your WordPress Dashboard, you'll see you'll be able to customize these component slugs from the Members accordion panel.

Single Member’s area

PS: if you need your Add-on to be compatible with BuddyPress 12.0.0 as well as with previous versions of BuddyPress, you can have a look at how the BP Attachments Add-on deals with the register_nav() & setup_nav() methods.

Adding your custom menu items to the Member's WP Admin Bar navigation

To let the logged in member easily reach their own pages, BuddyPress adds a specific menu to the WP Admin Bar. If your component needs to add its custom menu items to it, you need to override the BP_Component::setup_admin_bar() from your component’s class. Once you added your custom menu items arguments in a multidimensional array, as usual, you simply need to send them to parent::setup_admin_bar() so that BuddyPress insert them for you.

NB: unlike the bp_get_members_component_link() function which help you build a displayed user link in all BuddyPress versions, there's no equivalent function to have the loggedin user URL. In this case you can add the following backward compatibility method to your component's class to build this URL for all BuddyPress versions.

/**
 * Get the user logged in URL in BuddyPress >= 12.0.0 and older ones.
 *
 * @param array $path_chunks {
 *     An array of arguments. Optional.
 *
 *     @type string $single_item_component        The component slug the action is relative to.
 *     @type string $single_item_action           The slug of the action to perform.
 *     @type array  $single_item_action_variables An array of additional informations about the action to perform.
 * }
 * @return string The logged in user URL.
 */
public function get_loggedin_user_url( $path_chunks = array() ) {
	$user_url = '';

	// BuddyPress 12.0.0 is being used.
	if ( function_exists( 'bp_core_get_query_parser' ) ) {
		$user_url = bp_loggedin_user_url( bp_members_get_path_chunks( $path_chunks ) );

		// An older version of BuddyPress is being used
	} else {
		$user_url = bp_loggedin_user_domain();

		if ( $path_chunks ) {
			$action_variables = end( $path_chunks );
			if ( is_array( $action_variables ) ) {
				array_pop( $path_chunks );
				$path_chunks = array_merge( $path_chunks, $action_variables );
			}

			$user_url = trailingslashit( $user_url ) . trailingslashit( implode( '/', $path_chunks ) );
		}
	}

	return $user_url;
}

Once this method is in place, you'll just need to use it within your component’s setup_admin_bar() method. Another option is to use a specific function for this compatibility task as there’s a good chance you will need it in other parts of your code. You can have some examples of how to achieve this checking the way the BP Attachments Add-on is making sure to build user URLs for all BuddyPress versions.

class BP_Custom_AddOn_Component extends BP_Component {
	public function __construct() { /** Your component’s constructor code. */ }
	public function setup_globals( $bp_globals = array() ) { /** Your component’s code to set custom/BP globals. */ }
	public function includes( $files = array() ) { /** Your component’s code to include required files. */ }
	public function register_nav( $main_nav = array(), $sub_nav = array() ) { /** Your component’s code to register the member’s nav. */ }
	public function get_loggedin_user_url( $path_chunks = array() ) { /** The backcompat method to get the logged in user URL for your component. */ }

	/**
	 * Set up the component entries in the WordPress Admin Bar.
	 *
	 * @since BuddyPress 1.5.0
	 *
	 * @param array $wp_admin_bar A multidimensional array of nav item arguments.
	 */
	public function setup_admin_bar( $wp_admin_bar = array() ) {
		if ( is_user_logged_in() ) {

			// Add the "Custom" sub menu.
			$wp_admin_bar[] = array(
				'parent' => buddypress()->my_account_menu_id,
				'id'     => 'my-account-' . $this->id,
				'title'  => _x( 'Custom', 'My Account Custom sub nav', 'custom-text-domain' ),
				'href'   => $this->get_loggedin_user_url( array( $this->slug ) ),
			);

			// Add the "Default sub nav" sub menu.
			$wp_admin_bar[] = array(
				'parent'   => 'my-account-' . $this->id,
				'id'       => 'my-account-' . $this->id . 'default-sub-nav',
				'title'    => _x( 'Default sub nav name', 'My Account Custom sub nav', 'custom-text-domain' ),
				'href'     => $this->get_loggedin_user_url( array( $this->slug, 'default-subnav-slug' ) ),
				'position' => 10,
			);

			// Add the "Other sub nav" sub menu.
			$wp_admin_bar[] = array(
				'parent'   => 'my-account-' . $this->id,
				'id'       => 'my-account-' . $this->id . 'other-sub-nav',
				'title'    => _x( 'Other sub nav name', 'My Account Custom sub nav', 'custom-text-domain' ),
				'href'     => $this->get_loggedin_user_url( array( $this->slug, 'other-subnav-slug' ) ),
				'position' => 20,
			);
		}

		parent::setup_admin_bar( $wp_admin_bar );
	}
}

Here's what you should get:

WP Admin Bar’s Member menu

Parsing requests about your custom Add-on directory

Before looking at the method you need to override to parse requests about your component’s directory, let’s first make sure the setup_globals() method of your component is using the right BuddyPress globals: the ones to let it know your component has a directory area.

5 BP Specific globals are about adding this directory area to your component: $root_slug, $has_directory, $rewrite_ids, $directory_title, & $search_string. To generate and be able to parse requests about your component's directory page, you need (at least) to set the directory attribute of your component Rewrite IDs and the has_directory global to true. For example:

$bp_globals = array(
	// This what comes after your `site_url()`.
	'root_slug'       => 'custom-component',

	// I confirm my component has a directory area.
	'has_directory'   => true,

	/*
	 * This is new in BuddyPress 12.0.0: the BP Rewrites API globals.
	 * 
	 * If you specify the following 4 keys, BuddyPress will build the corresponding
	 * WordPress rewrite rules for you.
	 */ 
	'rewrite_ids'     => array(
		'directory'                    => 'custom_directory',
		'single_item'                  => 'custom_item',
		'single_item_action'           => 'custom_item_action',
		'single_item_action_variables' => 'custom_item_action_variables',
	),
	'directory_title' => __( 'Custom Directory', 'custom-text-domain' ),
	'search_string'   => __( 'Search custom items', 'custom-text-domain' ),
);

Rewrite rules about the $directory, $single_item, $single_item_action & $single_item_action_variables keys will automatically be generated by BuddyPress, if you use other/additional keys, you'll need to handle the corresponding rewrites rules from the add_rewrite_tags() & add_rewrite_rules() methods of your component.

WP Admin Bar’s Member menu

To get the above results, you first need to override the BP_Component::parse_query() method from your component’s class. Thanks to its $query argument you'll be able to check if the WP_Query (WordPress query) is about your component's directory: Using the WP_Query::get() method like this $query->get( $this->rewrite_ids['directory'] ) from your method, you'll know your component directory area is requested if 1 equals $query->get( $this->rewrite_ids['directory'] ). $this->rewrite_ids['directory'] value was set thanks to the $bp_globals you defined from the setup_globals() method of your components. The 3 others rewrite_ids can be accessed the same way:

Your goal is to map this rewrite IDs with the BuddyPress URI globals the plugin uses to load its content:

Below is an example of how your component's parse_query() could look like to perform this mapping.

class BP_Custom_AddOn_Component extends BP_Component {
	public function __construct() { /** Your component’s constructor code. */ }
	public function setup_globals( $bp_globals = array() ) { /** Your component’s code to set custom/BP globals. */ }
	public function includes( $files = array() ) { /** Your component’s code to include required files. */ }
	public function register_nav( $main_nav = array(), $sub_nav = array() ) { /** Your component’s code to register the member’s nav. */ }
	public function setup_admin_bar( $wp_admin_bar = array() ) { /** Your component’s code to generate the menu entries into the WordPress Admin Bar. */ }

	/**
	 * Parse the WP_Query and eventually display the component's directory or single item.
	 *
	 * @since 1.0.0
	 *
	 * @param WP_Query $query Required. See BP_Component::parse_query() for
	 *                        description.
	 */
	public function parse_query( $query ) {
		// This is a request about your component's directory area!
		if ( 1 === (int) $query->get( $this->rewrite_ids['directory'] ) ) {
			$bp = buddypress();

			// Set the Custom component as the BP Current component.
			$bp->current_component = 'custom';

			$custom_item_slug = $query->get( $this->rewrite_ids['single_item'] );

			// Set the BP current item, if provided.
			if ( $custom_item_slug ) {
				$bp->current_item = $custom_item_slug;

				$current_action = $query->get( $this->rewrite_ids['single_item_action'] );

				// Set the BP current action, if provided.
				if ( $current_action ) {
					$bp->current_action = $current_action;
				}

				$action_variables = $query->get( $this->rewrite_ids['single_item_action_variables'] );

				// Set BP action variables, if provided.
				if ( $action_variables ) {
					// Pretty links.
					if ( ! is_array( $action_variables ) ) {
						$bp->action_variables = explode( '/', ltrim( $action_variables, '/' ) );

						// Plain links.
					} else {
						$bp->action_variables = $action_variables;
					}
				}
			}

			// Set the BuddyPress queried object.
			if ( isset( $bp->pages->custom->id ) ) {
				$query->queried_object    = get_post( $bp->pages->custom->id );
				$query->queried_object_id = $query->queried_object->ID;
			}
		}

		// Do not forget to send back the query to the `BP_Component` parent method.
		parent::parse_query( $query );
	}
}

Once you analyzed and parsed the WordPress query to set the BuddyPress URI globals, it's a good practice to send back the $query to the parent class to keep BuddyPress predictable as it then fires a dynamic hook about your component.

Now you've set BuddyPress URI globals, you need to use the BP Theme Compat API so that BuddyPress themes or BuddyPress Template packs can override the way the content of your Add-on directory is displayed.

Below is a quick workaround you can use to finally get the result shown in the screen capture.

/**
 * Sets the template to load for the Custom directory.
 */
function bp_custom_add_on_directory_screen() {
	if ( ! bp_is_current_component( 'custom' ) || bp_is_user() ) {
		return;
	}

	bp_update_is_directory( true, 'custom' );

	// This is where you should use a custom template extending BP Templates stacks.
	bp_core_load_template( 'custom/index' );
}
add_action( 'bp_screens', 'bp_custom_add_on_directory_screen' );

/**
 * Sets the Custom Add-on directory content dummy post.
 */
function bp_custom_add_on_set_dummy_post() {
	// Use the Custom Add-on directory title by default.
	$title = bp_get_directory_title( 'custom' );

	bp_theme_compat_reset_post(
		array(
			'ID'             => 0,
			'post_title'     => $title,
			'post_author'    => 0,
			'post_date'      => 0,
			'post_content'   => '',
			'post_type'      => 'page',
			'post_status'    => 'publish',
			'is_page'        => true,
			'comment_status' => 'closed',
		)
	);
}

/**
 * Outputs the Custom directory content.
 */
function bp_custom_add_on_set_content_template() {
	/*
	 * You should use a specific template extending the BP Templates stack.
	 * eg: /path-to-your-add-on-templates/custom/index.php`.
	 *
	 * Then you'd need to buffer the template content doing:
	 * $template = bp_buffer_template_part( 'custom/index', null, false );
	 *
	 * This would let themes/template packs override your template if they need more
	 * customization.
	 */

	$template = sprintf( '<p>%s</p>', esc_html__( 'It works!', 'custom-text-domain' ) );

	if ( bp_current_item() ) {
		$template .= sprintf(
			'<p>%1$s <strong>%2$s</strong></p>',
			esc_html__( 'Current item is:', 'custom-text-domain' ),
			esc_html( bp_current_item() )
		);
	}

	if ( bp_current_action() ) {
		$template .= sprintf(
			'<p>%1$s <strong>%2$s</strong></p>',
			esc_html__( 'Current item action is:', 'custom-text-domain' ),
			esc_html( bp_current_action() )
		);
	}

	if ( bp_action_variables() ) {
		$template .= sprintf(
			'<p>%1$s <strong>%2$s</strong></p>',
			esc_html__( 'Current item action variables are:', 'custom-text-domain' ),
			implode( ', ', array_map( 'esc_html', bp_action_variables() ) )
		);
	}

	return $template;
}

/**
 * Sets the Custom Add-on directory theme compat screens.
 */
function bp_custom_add_on_set_directory_theme_compat() {
	if ( bp_is_current_component( 'custom' ) && ! bp_is_user() ) {
		add_action( 'bp_template_include_reset_dummy_post_data', 'bp_custom_add_on_set_dummy_post' );
		add_filter( 'bp_replace_the_content', 'bp_custom_add_on_set_content_template' );
	}
}
add_action( 'bp_setup_theme_compat', 'bp_custom_add_on_set_directory_theme_compat' );

Activity database tables

When first activated, the Activity component creates 2 tables. One to store activity stream items ({$table_prefix}bp_activity), the other to store metadata about items ({$table_prefix}bp_activity_meta).

[!NOTE]
The {$table_prefix} value is wp_ by default but it can be customized within the WordPress wp-config.php file.

[!IMPORTANT]
The {$table_prefix}bp_activity is always created even if the Activity component is not active. BuddyPress is using this table to log members last site activity date/time.

{$table_prefix}bp_activity

This table stores all activities (such as posts, comments, updates) made by users in BuddyPress. It also logs user interactions or community events.

Name Type Description
id BIGINT The unique ID for each activity entry.
user_id BIGINT The ID of the user who performed the activity.
component VARCHAR Specifies which BuddyPress component (e.g., groups, members) the activity is associated with.
type VARCHAR Type of activity (e.g., new post, comment, group creation).
action TEXT Human-readable description of the action performed[^1].
content LONGTEXT Main content of the activity.
primary_link TEXT The link to the activity item[^2].
item_id BIGINT ID associated with the primary item (group or other).
secondary_item_id BIGINT Additional context ID, if applicable.
date_recorded DATETIME When the activity was recorded.
hide_sitewide TINYINT Whether the activity is hidden from the sitewide activity stream.
mptt_left INT Node boundary start for activity or activity comment.
mptt_right INT Node boundary end for activity or activity comment.
is_spam TINYINT Whether the activity item is marked as spam.

{$table_prefix}bp_activity_meta

Stores metadata associated with activity entries.

Name Type Description
id BIGINT Meta ID
activity_id BIGINT The ID of the associated activity.
meta_key VARCHAR Metadata key.
meta_value LONGTEXT Metadata value[^3].

[^1]: BuddyPress is re-generating this action during runtime to make it translatable. [^2]: BuddyPress may re-generate this primary_link at runtime for specific activity types, e.g.: it uses post's permalink for new_blog_post typed activities. [^3]: Arrays or Objects are stored as serialized data.

Extending BuddyPress Activity Embeds

BuddyPress registers a custom oEmbed endpoint that handles activity embeds using the WordPress REST API. The endpoint allows you to fetch and display embedded activity items.

oEmbed REST API Endpoint:

/wp-json/oembed/1.0/embed/activity?url=URL_TO_ACTIVITY_ITEM

Supported Parameters:

Example usage:

curl "https://example.com/wp-json/oembed/1.0/embed/activity?url=https://example.com/members/user/activity/123"

Extending BuddyPress Activity Embeds

Adding Custom Hooks

BuddyPress allows developers to extend and modify the embed functionality through various hooks and filters.

Key Filters:

Example: Adding a custom element to the embed footer

function my_custom_embed_footer() {
    echo '<div>Custom footer content</div>';
}
add_action( 'get_template_part_assets/embeds/footer', 'my_custom_embed_footer' );

Customizing the oEmbed Response

You can modify the oEmbed response data using the BP_Activity_oEmbed_Extension class by hooking into its methods. This class manages the activity embed endpoint, ensuring proper response formatting and validation.

Example:

class My_Custom_BP_Activity_oEmbed extends BP_Activity_oEmbed_Extension {
    protected function set_oembed_response_data( $item_id ) {
        $response = parent::set_oembed_response_data( $item_id );
        // Add custom data to the response.
        $response['custom_field'] = 'My custom data';
        return $response;
    }
}

Blogs database tables

When first activated and if the WordPress site uses a multisite configuration, the Blogs component creates 2 tables. One to store users relationship to blogs ({$table_prefix}bp_user_blogs), the other to store metadata about blogs ({$table_prefix}bp_user_blogs_blogmeta).

[!NOTE]
The {$table_prefix} value is wp_ by default but it can be customized within the WordPress wp-config.php file.

{$table_prefix}bp_user_blogs

This table stores users relationship to blogs.

Name Type Description
id BIGINT The unique ID for each user/blog relationships.
user_id BIGINT The ID of the user who has a relationship with the blog.
blog_id BIGINT The ID of the blog, the user has a relationship with.

{$table_prefix}bp_user_blogs_blogmeta

Stores metadata associated with blog entries.

Name Type Description
id BIGINT Meta ID
blog_id BIGINT The ID of the associated blog.
meta_key VARCHAR Metadata key.
meta_value LONGTEXT Metadata value[^1].

[^1]: Arrays or Objects are stored as serialized data.

Friends database tables

When first activated, the Friends component creates a table to store users friendships ({$table_prefix}bp_friends).

[!NOTE]
The {$table_prefix} value is wp_ by default but it can be customized within the WordPress wp-config.php file.

{$table_prefix}bp_friends

This table stores the friendship connections between users.

Name Type Description
id BIGINT Unique ID for each friendship connection.
initiator_user_id BIGINT The user ID who sent the friend request.
friend_user_id BIGINT The user ID who received the friend request.
is_confirmed TINYINT Whether the friendship has been confirmed (1) or is pending (0).
is_limited TINYINT Whether the friendship has any limitations [^1].
date_created DATETIME When the friendship was initiated.

[^1]: Not used anymore. Kept for backwards compatibility reasons.

Groups database tables

When first activated, the Groups component creates 3 tables. One to store groups characteristics ({$table_prefix}bp_groups), another one to store metadata about items ({$table_prefix}bp_groups_groupmeta), and one to store groups memberships ({$table_prefix}bp_groups_members).

[!IMPORTANT]
The Groups component also uses the BP Invitation API to manage single groups invitations. The database table used by this API is always installed and is documented into the Members database tables chapter.

[!NOTE]
The {$table_prefix} value is wp_ by default but it can be customized within the WordPress wp-config.php file.

{$table_prefix}bp_groups

This table stores all groups (such as public, private or hidden ones) created by users in BuddyPress.

Name Type Description
id BIGINT Unique ID for the group.
creator_id BIGINT User ID of the group creator.
name VARCHAR Name of the group.
slug VARCHAR Unique slug for the group [^1].
description LONGTEXT Group description.
status VARCHAR Group visibility status (public, private, hidden).
parent_id BIGINT Parent group ID (if applicable) [^2].
enable_forum TINYINT Whether the group has forums enabled [^3].
date_created DATETIME When the group was created.

{$table_prefix}bp_groups_groupmeta

Stores metadata associated with groups.

Name Type Description
id BIGINT Meta ID
group_id BIGINT The ID of the associated group.
meta_key VARCHAR Metadata key.
meta_value LONGTEXT Metadata value[^4].

{$table_prefix}bp_groups_members

Stores metadata associated with groups.

Name Type Description
id BIGINT Unique group membership ID
group_id BIGINT The ID of the associated group.
user_id BIGINT The ID of the user.
inviter_id BIGINT The ID of the user who invited the member (if applicable).
is_admin TINYINT Whether the user is an admin of the group.
is_mod TINYINT Whether the user is a moderator of the group
user_title VARCHAR The role or title of the user within the group.
date_modified DATETIME When the membership was last modified.
comments LONGTEXT Private group membership request message [^5].
is_confirmed TINYINT Whether the membership has been confirmed.
is_banned TINYINT Whether the user is banned from the group.
invite_sent TINYINT Whether an invitation has been sent.

[^1]: the group's slug is the URL portion used to reach a single group (e.g.: site.url/groups/{$group-slug}). [^2]: the parent_id field is not used by BuddyPress internally to provide a groups hierarchy feature leaving this part to BuddyPress Add-ons. See changeset 11095. [^3]: the enable_forum is used by the bbPress plugin to inform the corresponding group has a forum associated to it. [^4]: Arrays or Objects are stored as serialized data. [^5]: Not used anymore. Kept for backwards compatibility reasons.

Group Extension API

The group extension API makes it very easy to add custom creation steps, edit screens, navigation items and pages to a group. It essentially allows you to create fully functional extensions to BuddyPress created groups.

The Group Extension API consists of a base class called BP_Group_Extension, which you extend in your own add-on. BP_Group_Extension does most of the work necessary to integrate your content into BP group – creating new navigation tabs, registering a step during group creation, etc.

NB: the group extension requires the Groups component to be active. Please make sure to wrap your extended class in a if ( bp_is_active( 'groups' ) ) : check.

Located inside the /bp-groups/classes directory, the BP_Group_Extension class will help you to organize your custom group extension. BuddyPress group extensions are registered into the $group_extensions property of the buddypress()->groups global using the name of your custom class. This registration step needs to be hooked to the bp_init action at a priority lower than 11 (you can omit the hook $priority argument to use the default one - 10) and is done passing the name of your class to the bp_register_group_extension() function. Below is an example of how you can register your group extension in BuddyPress.

/**
 * Registers the custom group extension.
 */
function bp_custom_add_on_register_group_extension() {
	bp_register_group_extension( 'BP_Custom_AddOn_Group_Extension' );
}
add_action( 'bp_init', 'bp_custom_add_on_register_group_extension' );

Building your group extension’s class

It’s a WordPress good practice to put the code of your class into a file having a class- prefix followed by your class name where caps are replaced by their corresponding lower case value and underscores by dashes. As our custom group extension's class is named BP_Custom_Group_Extension, we are putting its code inside a class-bp-custom-group-extension.php file. Let's built it making sure you will inherit from the BP_Component parent class using the extends keyword.

class BP_Custom_Group_Extension extends BP_Group_Extension {
	/*
	 * The properties and methods of for your group extension's class.
	 */ 
}

Adding the constructor of your class

This is where you are using the BP_Group_Extension::init() method to configure your custom group extension. This method expects an associative array where specific keys will be used to define the name & URL slug for your group extension tab within groups, who can access to it, and init additional screens such as the one BuddyPress can load during the group's creation process, or the one to let group Administrators customize some settings about your group extension. Let's build a very basic tab that will be displayed on each single groups.

Basic group extension

To get this result, here's how you need to define the arguments of the parameter you will send to the parent::init() method at the end of your constructor.

if ( bp_is_active( 'groups' ) ) {
	/**
	 * BP Custom group extension Class.
	 */
	class BP_Custom_AddOn_Group_Extension extends BP_Group_Extension {
		/**
		 * Your group extension's constructor.
		 */
		public function __construct() {
			$args = array(
				'slug'              => 'custom-group-extension',
				'name'              => __( 'Custom group extension', 'custom-text-domain' ),
				'nav_item_position' => 105,
				'access'            => 'anyone',
				'show_tab'          => 'anyone',
			);

			parent::init( $args );
		}

		/**
		 * Outputs the content of your group extension tab.
		 *
		 * @param int|null $group_id ID of the displayed group.
		 */
		public function display( $group_id = null ) {
			printf( '<p>%1$s %2$s</p>', esc_html__( 'It works! The displayed group ID is', 'custom-text-domain' ), $group_id );
		}
	}
}

The above code early introduced the display() method of your group extension's class so that something is actually displayed into groups! Before looking to it more in details, let's first list all possible keys and values for the $args configuration array.

Possible arguments for your configuration array

As we've just seen, the __construct() method of your group extension class should be used to pass a set of arguments to the parent::init( $args ) method. Below are these $args possible keys and values:

slug

(required) A unique string identifier for your group extension. Used, among other places, in the construction of URLs.

name

(required) The translatable name of your extension. Used as the default value for navigation items and page titles.

access

(optional) Which users can visit the group extension’s tab. Possible values: 'anyone', 'loggedin', 'member', 'mod', 'admin' or 'noone'. ('member', 'mod', 'admin' refer to user’s role in the current group.) Defaults to 'anyone' for public groups and 'member' for private groups. Note that the 'mod' level targets only moderators, so if you want to allow access for group moderators and administrators, specify array( 'mod', 'admin' ). This argument was introduced in BuddyPress 2.1.0.

show_tab

(optional) Which users can see the group extension’s navigation tab. Possible values: 'anyone', 'loggedin', 'member', 'mod', 'admin' or 'noone'. ('member', 'mod', 'admin' refer to user’s role in the current group.) Defaults to 'anyone' for public groups and 'member' for private groups. Note that the 'mod' level targets only moderators, so if you want to show the tab to group moderators and administrators, specify array( 'mod', 'admin' ). This argument was introduced in BuddyPress 2.1.0.

show_tab_callback

(optional) The name of the function to use to define the show_tab argument. If you need to check for a specific setting to define whether or not your group extension tab should be shown to members, the static show_tab argument won't reply to your need. Use the show_tab_callback argument so that your callback function will be called once BuddyPress has set everything about the displayed group. Your callback function needs to return one of the possible values of the show_tab one. This argument was introduced in BuddyPress 12.0.0.

nav_item_position

(optional) An integer describing where your extension’s tab should appear. A number between 1 and 100 is recommended. Defaults to 81.

nav_item_name

(optional) The string you want to appear in the navigation tab for your group extension. Defaults to the value of the name argument, described above.

template_file

(optional) The template file that BuddyPress will use as a wrapper to display the content of your group extension. Defaults to groups/single/plugins.php. This template is provided by built-in BP Template Packs (nouveau & legacy). If you are building a BuddyPress standalone theme, please make sure to provide this template.

screens

(optional) A multi-dimensional array of options related to the three secondary “screens” available to group extensions: create (the step dedicated to the extension during the group creation process), edit (the subtab dedicated to the extension under the Admin tab of the group), and admin (the extension’s metabox that appears on the group page when editing via the Groups Administration Dashboard panels). Each of these screens has a set of configuration options, to be described below. Note that all config values are optional, and you only need to override those values where you want to change the default – BuddyPress will parse your screens array, using your provided values when available, otherwise falling back on the defaults.

Available Methods for your group extension’s class

BP_Group_Extension has built-in support for a number of different customization methods, which you can override in your group extension’s class as needed.

display()

The most prominent of these methods is display(), which BuddyPress uses to generate the output of the add-on’s main tab. It includes the $group_id argument so that you can customize your output according to the current displayed group. Your display() method should echo markup, which BuddyPress will automatically place into the proper template. As a reminder, below is the code we used in our very basic example of a group extension's class.

if ( bp_is_active( 'groups' ) ) {
	class BP_Custom_AddOn_Group_Extension extends BP_Group_Extension {
		public function __construct() { /* Your group extension's constructor. */ }

		/**
		 * Outputs the content of your group extension tab.
		 *
		 * @param int|null $group_id ID of the displayed group.
		 */
		public function display( $group_id = null ) {
			// You need to echo the markup.
			printf( '<p>%1$s %2$s</p>', esc_html__( 'It works! The displayed group ID is', 'custom-text-domain' ), $group_id );
		}
	}
}

Other screen methods

For the three “screen” contexts – create, edit, and admin – a flexible system allows you to customize the way that your group extension’s screens work, without unnecessary reproduction of code. Your group extension should, at minimum, provide the following two methods if you defined one or more screen context into your configuration array:

NB: these 2 methods include the $group_id argument so that you can customize your output/handler according to the current group being created, edited or administrated.

Let's improve our example of basic group extension including a feature to let the creator/administrator of the group decide whether they want to "activate" the group extension main tab for their group.

Create Screen Edit Screen Admin Screen
Create screen Edit screen Admin screen

As shown above, we need to output a form on the group’s create, edit & admin screens. The first step is to edit the configuration array ($args) the __construct() method is sending to BP_Group_Extension::init() so that it includes a $screens argument and a $show_tab_callback argument. The first will define the screens we need to add, and the second one will set the callback function to use to check whether to display the group’s extension main tab or not. Here's how the configuration array should look like:

$args = array(
	'slug'              => 'custom-group-extension',
	'name'              => __( 'Custom group extension', 'custom-text-domain' ),
	'nav_item_position' => 105,
	'access'            => 'anyone',

	// Set the callback function defining the `$show_tab` argument dynamically.
	'show_tab_callback' => array( $this, 'show_tab' ),

	// Define the screens using default screen settings.
	'screens'           => array(
		'edit'   => array(),
		'create' => array(),
		'admin'  => array(),
	),
);

NB: if you need your group extension to be back compatible with version of BuddyPress < 12.0.0, you'll need to add a conditional statement to use the $show_tab argument instead of the $show_tab_callback one. Here’s an example of how to add it:

// BuddyPress < 12.0.0 or BuddyPress >= 12.0.0 with the BP Classic backcompat plugin active.
if ( ! function_exists( 'bp_core_get_query_parser' ) || 'legacy' === bp_core_get_query_parser() ) {
	$args['show_tab'] = $this->show_tab();
	unset( $args['show_tab_callback'] );
}

NB: note that in the above code, we are not setting the callback function but running it. This means as it doesn’t include the $group_id in this case, you’ll need to use the bp_get_current_group_id() to set it within your show_tab() method. For example:

/**
 * Checks whether the main group extension’s tab should be displayed.
 *
 * @param int|null $group_id ID of the displayed group.
 * @return string 'anyone' if the group extension’s tab should be displayed. 'noone' otherwise.
 */
public function show_tab( $group_id = null ) {
	if ( ! $group_id ) {
		$group_id = bp_get_current_group_id();
	}

	$show_tab = 'noone';
	if ( $group_id && groups_get_groupmeta( $group_id, 'bp_custom_group_extension_is_active' ) ) {
		$show_tab = 'anyone';
	}

	return $show_tab;
}

The second step is to code the settings_screen() & settings_screen_save() methods so that each screen will output a form and handle its submission. Here's how these should look like into your group extension’s class:

if ( bp_is_active( 'groups' ) ) {
	class BP_Custom_AddOn_Group_Extension extends BP_Group_Extension {
		public function __construct() { /* Your group extension's constructor. */ }
		public function display( $group_id = null ) { /* Outputs the content of your group extension tab. */ }

		/**
		 * Outputs a form to activate the extension on 'edit', 'create' & 'admin' screens.
		 *
		 * @param int|null $group_id ID of the displayed group.
		 */
		public function settings_screen( $group_id = null ) {
			$active = (int) groups_get_groupmeta( $group_id, 'bp_custom_group_extension_is_active' );
			printf(
				'<label><input type="checkbox" name="bp_custom_group_extension_is_active" value="1" %1$s>%2$s</input></label>
				<input type="hidden" name="bp_custom_group_extension_was_active" value="%3$s">',
				checked( $active, true, false ),
				esc_html__( 'I want to activate the custom group extension!', 'custom-text-domain' ),
				$active
			);
		}

		/**
		 * Activate or Deactivate the group extension from 'edit', 'create' or 'admin' screens.
		 *
		 * @param int|null $group_id ID of the displayed group.
		 */
		public function settings_screen_save( $group_id = null ) {
			$was_active = 0;
			$is_active  = 0;

			if ( isset( $_REQUEST['bp_custom_group_extension_was_active'] ) ) {
				$was_active = intval( wp_unslash( $_REQUEST['bp_custom_group_extension_was_active'] ) );

				if ( isset( $_REQUEST['bp_custom_group_extension_is_active'] ) ) {
					$is_active = intval( wp_unslash( $_REQUEST['bp_custom_group_extension_is_active'] ) );
				}

				if ( $was_active && ! $is_active ) {
					groups_delete_groupmeta( $group_id, 'bp_custom_group_extension_is_active' );
				} elseif ( ! $was_active && $is_active ) {
					groups_update_groupmeta( $group_id, 'bp_custom_group_extension_is_active', $is_active );
				}
			}
		}
	}
}

Finally, If your extension requires further customization to one or more of the screens, BuddyPress provides the following methods, which are context-specific:

NB: these methods include the $group_id argument so that you can customize your output/handler according to the current group being updated.

If your extension contains any of these methods, BuddyPress will use them when appropriate. Otherwise, the generic settings_screen() or settings_screen_save() will be used.

Members database tables

When first activated, the Members component creates 2 tables. One to store invitations to join the site or a Groups component single item ({$table_prefix}bp_invitations), the other to store information about people who opted out to site invitations ({$table_prefix}bp_optouts).

[!NOTE]
The {$table_prefix} value is wp_ by default but it can be customized within the WordPress wp-config.php file.

{$table_prefix}bp_invitations

This table stores invitations to join the site or a Groups component single item.

Name Type Description
id BIGINT The unique ID for each user/blog relationships.
user_id BIGINT ID of the invited user.
inviter_id BIGINT ID of the user who created the invitation.
invitee_email VARCHAR Email address of the invited user.
class VARCHAR Name of the invitations class (the PHP object name) [^1].
item_id BIGINT ID of the object associated with the invitation and class
secondary_item_id BIGINT Secondary ID associated with the invitation and class
type VARCHAR Type of record this is: 'invite' or 'request'.
content LONGTEXT Extra content the inviting user added to their invitation
date_modified DATETIME Date the invitation was last modified.
invite_sent TINYINT Whether the invitation has been sent or is still a draft.
accepted TINYINT Whether the invitation has been accepted or is still pending.

{$table_prefix}bp_optouts

Stores metadata associated with opt-out entries.

Name Type Description
id BIGINT ID of the opt-out record.
email_address_hash VARCHAR Hash of the email which was used to opt-out.
user_id BIGINT The ID of the user that generated the contact that resulted in the opt-out.
email_type VARCHAR The type of email contact that resulted in the opt-out.
date_modified DATETIME The date the opt-out was last modified.

[^1]: BuddyPress currently uses 2 classes: BP_Groups_Invitation_Manager to deal with Groups component single item invitations and BP_Members_Invitation_Manager to deal with site invitations.

Messages database tables

When first activated, the Messages component creates 4 tables. One is storing sent messages data ({$table_prefix}bp_messages_messages), the second one is about managing messages recipients ({$table_prefix}bp_messages_recipients) and the last one is used to store meta data about messages ({$table_prefix}bp_messages_meta).

[!NOTE]
The {$table_prefix} value is wp_ by default but it can be customized within the WordPress wp-config.php file.

{$table_prefix}bp_messages_messages

This table stores private messages data.

Name Type Description
id BIGINT Unique message ID.
thread_id BIGINT ID of the conversation thread, the message belongs to.
sender_id BIGINT ID of the user who inited the conversation thread.
subject VARCHAR Subject of the message.
message LONGTEXT The message content.
date_sent DATETIME The date when the message was sent.

{$table_prefix}bp_messages_recipients

This table stores messages recipients data.

Name Type Description
id BIGINT Unique field ID.
user_id BIGINT ID of the user involved into the private conversation.
thread_id BIGINT ID of the conversation thread, the user is involved in.
unread_count INT The number of unread messages for the thread and user.
sender_only TINYINT Whether the recipient is the only sender or not.
is_deleted TINYINT Whether the recipient has deleted the message or not.

{$table_prefix}bp_messages_meta

This table is used to store meta data about messages.

Name Type Description
id BIGINT Unique meta ID.
message_id BIGINT ID of the message entry, the meta data relates to.
meta_key VARCHAR Metadata key.
meta_value LONGTEXT Metadata value[^1].

[^1]: Arrays or Objects are stored as serialized data.

Notifications database tables

When first activated, the Notifications component creates 2 tables. One to store user notifications ({$table_prefix}bp_notifications), the other to store metadata about notifications ({$table_prefix}bp_notifications_meta).

[!NOTE]
The {$table_prefix} value is wp_ by default but it can be customized within the WordPress wp-config.php file.

{$table_prefix}bp_notifications

This table stores notifications about user interactions.

Name Type Description
id BIGINT Unique notification ID.
user_id BIGINT The ID of the user receiving the notification.
item_id BIGINT Primary item related to the notification.
secondary_item_id BIGINT Secondary item, if applicable.
component_name VARCHAR Name of the BuddyPress component (e.g.: groups, messages).
component_action VARCHAR Action triggering the notification (e.g., group invite, message received).
date_notified DATETIME When the notification was created.
is_new TINYINT Whether the notification is new.

{$table_prefix}bp_notifications_meta

Stores metadata associated with notifications.

Name Type Description
id BIGINT Meta ID
notifiction_id BIGINT The ID of the associated notification.
meta_key VARCHAR Metadata key.
meta_value LONGTEXT Metadata value[^1].

[^1]: Arrays or Objects are stored as serialized data.

xProfile database tables

When first activated, the xProfile component creates 4 tables to store xProfile information about your members. The first one is storing groups of profile fields data ({$table_prefix}bp_xprofile_groups), the second one is about managing profile fields data ({$table_prefix}bp_xprofile_fields) that is relative to profile field groups. The third table is dealing with user information for the created profile fields ({$table_prefix}bp_xprofile_data) and the fourth one is used to store meta data about profile groups, fields and data ({$table_prefix}bp_xprofile_meta).

[!NOTE]
The {$table_prefix} value is wp_ by default but it can be customized within the WordPress wp-config.php file.

{$table_prefix}bp_xprofile_groups

This table stores groups of profile fields data.

Name Type Description
id BIGINT Unique ID for the profile fields group.
name VARCHAR Name of the profile fields group.
description MEDIUMTEXT Description of the profile fields group.
group_order BIGINT Informs about the display order of profile fields group inside a loop.
can_delete TINYINT Whether the profile fields group can be deleted or not[^1].

{$table_prefix}bp_xprofile_fields

This table stores profile fields data.

Name Type Description
id BIGINT Unique field ID.
group_id BIGINT ID of the profile fields group the field belongs to.
parent_id BIGINT Parent field ID (for hierarchical fields).
type VARCHAR The type of field (e.g.: text, checkbox, select).
name VARCHAR The name of the field.
description LONGTEXT Description of the field.
is_required TINYINT Whether the field is required.
is_default_option TINYINT Whether this is the default option (in case of multiple choice parent field).
field_order BIGINT Informs about the display order of the field inside a profile fields group.
option_order BIGINT Informs about the display order of the field inside a multiple choice parent field.
order_by VARCHAR The sorting method for the field.
can_delete TINYINT Whether the profile fields can be deleted or not[^2].

{$table_prefix}bp_xprofile_data

This table is dealing with user information for the created profile fields.

Name Type Description
id BIGINT Unique profile data ID.
field_id BIGINT ID of the profile field, user data is attached to.
user_id BIGINT ID of the user, data belongs to
value LONGTEXT Value of the profile field for the user.
last_updated DATETIME When the field data was updated for the last time.

{$table_prefix}bp_xprofile_meta

This table is used to store meta data about profile groups, fields and data.

Name Type Description
id BIGINT Unique meta ID.
object_id BIGINT ID of the profile group, field or data entry, the meta data relates to.
object_type VARCHAR Type of object: 'group', 'field', or 'data'.
meta_key VARCHAR Metadata key.
meta_value LONGTEXT Metadata value[^3].

[^1]: for instance the "base" default BuddyPress profile fields group cannot be deleted. [^2]: for instance the "name" default BuddyPress profile field cannot be deleted. [^3]: Arrays or Objects are stored as serialized data.

Using Ajax requests in BuddyPress

Starting in BuddyPress 12.0.0, if your Ajax callback needs to get values about BP URI globals such as the displayed user, the current component, the current action or current action variables, you'll need to register your Ajax action so that BuddyPress is informed you're expecting these globals' values.

To avoid running the WP() request analysis at each Ajax request, BuddyPress is only doing so for the registered Ajax actions.

To register your Ajax action, you simply need to use the bp_ajax_register_action() once the bp_init action hook has been fired.

/**
 * Register a BP Ajax action.
 */
function register_your_ajax_action() {
	bp_ajax_register_action( 'your_ajax_action' );
}
add_action( 'bp_init', 'register_your_ajax_action' );

Activity REST API routes

BuddyPress activities inform about actions and interactions of the community site’s members. Members can share public announcements and react about these by commenting or favoriting them. Activities also log events generated by the other BuddyPress components, for instance, when two users become friends.

[!IMPORTANT] The Activity component is an optional one. This means the activity endpoints will only be available if the component is active on the community site.

Schema

The schema defines all the fields that exist for an activity object.

Property Description
id Unique identifier for the activity item.
JSON data type: integer.
Read only.
Context: embed, view, edit.
primary_item_id The ID of some other object primarily associated with this activity item.
JSON data type: integer.
Context: embed, view, edit.
secondary_item_id The ID of some other object also associated with this activity item.
JSON data type: integer.
Context: embed, view, edit.
user_id The ID for the author of the activity item.
JSON data type: integer.
Read only.
Context: embed, view, edit.
link The permalink to this activity item on the site.
JSON data type: string, format: URI.
Read only.
Context: embed, view, edit.
component The BuddyPress component the activity item relates to.
JSON data type: string.
One of: the active BuddyPress component names.
Context: embed, view, edit.
type The type of the activity (e.g.: activity_update).
JSON data type: string.
One of: the registered activity types.
Context: embed, view, edit.
title The description of the activity item’s type (eg: Username posted an update).
JSON data type: string.
Read only.
Context: embed, view, edit.
content The raw and rendered contents of the activity item.
JSON data type: object (properties: raw, rendered ).
Context: embed, view, edit.
date The date the activity item was published, in the site’s timezone.
JSON data type: string | null, format: date-time.
Read only.
Context: embed, view, edit.
date_gmt The date the activity item was published, as GMT.
JSON data type: string | null, format: date-time.
Read only.
Context: embed, view, edit.
status Whether the activity has been marked as spam or not.
JSON data type: string.
Read only.
One of: published, spam.
Context: embed, view, edit.
comments A list of comments which are children of the activity item.
JSON data type: array.
Read only.
Context: embed, view, edit.
comment_count Total number of comments which are children of the activity item.
JSON data type: integer.
Read only.
Context: embed, view, edit.
hidden Whether the activity item should be sitewide hidden or not.
JSON data type: boolean.
Read only.
Context: embed, edit.
favorited Whether the activity item has been favorited by the current user.
JSON data type: boolean.
Read only.
Context: embed, view, edit.
user_avatar[^1] Avatar URLs for the author of the activity item (Full & Thumb sizes).
JSON data type: object (properties: full, and thumb).
Read only.
Context: embed, view, edit.

List Activities

Arguments

Name Description
context Scope under which the request is made; determines fields present in response.
JSON data type: string.
Default: view.
One of: view, embed, edit.
page Current page of the collection.
JSON data type: integer.
Default: 1.
per_page Maximum number of activity items to be returned in result set.
JSON data type: integer.
Default: 10.
search Limit results to those matching a string.
JSON data type: string.
exclude Ensure result set excludes specific IDs.
JSON data type: array.
Default: [].
include Ensure result set includes specific IDs.
JSON data type: array.
Default: [].
order Order sort attribute ascending or descending.
JSON data type: string.
Default: desc.
One of: desc, asc.
after Limit result set to activity items published after a given ISO8601 compliant date.
JSON data type: string | null, format: date-time.
user_id Limit result set to activity items created by a specific user (ID).
JSON data type: integer.
Default: 0.
status Limit result set to activity items with a specific status.
JSON data type: string.
Default: ham_only.
One of: ham_only, spam_only, all.
scope Limit result set to activity items with a specific scope.
JSON data type: string.
One of: just-me, friends, groups, favorites, mentions.
group_id Limit result set to activity items created by a specific group.
JSON data type: integer.
Default: 0.
site_id Limit result set to activity items created by a specific site.
JSON data type: integer.
Default: 0.
primary_id Limit result set to activity items with a specific prime association ID.
JSON data type: integer.
Default: 0.
secondary_id Limit result set to activity items with a specific secondary association ID.
JSON data type: integer.
Default: 0.
component Limit result set to activity items with a specific BuddyPress component.
JSON data type: string.
One of: the active BuddyPress component names.
type Limit result set to activity items with one or more specific activity type.
JSON data type: array.
One of: the registered activity types.
display_comments No comments by default, stream for within stream display, threaded for below each activity item.
JSON data type: string.
Default: ''.

Definition

GET /buddypress/v2/activity

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/activity?context=view&type=activity_update', {
	method: 'GET',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.table( data );
} );

JSON Response

Create an activity item

Logged in users can create sitewide activity items. When the Groups component is active, only group members can create activity items within the corresponding group.

Arguments

Name Description
primary_item_id The ID of some other object primarily associated with this one.
JSON data type: integer.
secondary_item_id The ID of some other object also associated with this one.
JSON data type: integer.
link The permalink to this activity item on the site.
JSON data type: string, format: URI.
component The active BuddyPress component the activity relates to.
JSON data type: string.
One of: the active BuddyPress component names.
Default: activity.
type The type of the activity (e.g.: activity_update).
JSON data type: string.
One of: the registered activity types.
Default: activity_update.
content Allowed HTML content for the activity.
JSON data type: string.
hidden Whether the activity item should be sitewide hidden or not.
JSON data type: boolean.

Definition

POST /buddypress/v2/activity

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/activity', {
	method: 'POST',
	headers: requestHeaders,
	body: JSON.stringify(
		{
			content: 'bapuu is the BuddyPress wapuu',
		}
	),
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Retrieve a specific activity item

Arguments

Name Description
id A unique numeric ID for the activity item. Required.
JSON data type: integer.
context Scope under which the request is made; determines fields present in response.
JSON data type: string.
Default: view.
One of: view, embed, edit.

Definition

GET /buddypress/v2/activity/<id>

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/activity/18', {
	method: 'GET',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Update a specific activity item

Arguments

Name Description
id A unique numeric ID for the activity item. Required.
JSON data type: integer.
primary_item_id The ID of some other object primarily associated with this one.
JSON data type: integer.
primary_item_id The ID of some other object also associated with this one.
JSON data type: integer.
link The permalink to this activity item on the site.
JSON data type: string, format: URI.
component The active BuddyPress component the activity relates to.
JSON data type: string.
One of: the active BuddyPress component names.
Default: activity.
type The type of the activity (e.g.: activity_update). Required.
JSON data type: string.
One of: the registered activity types.
Default: activity_update.
content Allowed HTML content for the activity.
JSON data type: string.
hidden Whether the activity item should be sitewide hidden or not.
JSON data type: boolean.

Definition

PUT /buddypress/v2/activity/<id>

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/activity/18', {
	method: 'PUT',
	headers: requestHeaders,
	body: JSON.stringify(
		{
			content: 'bapuu, The BP wapuu.',
			type: 'activity_update',
		}
	),
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Delete a specific activity item

Arguments

Name Description
id A unique numeric ID for the activity item. Required.
JSON data type: integer.

Definition

DELETE /buddypress/v2/activity/<id>

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/activity/18', {
	method: 'DELETE',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Add or remove a specific activity item from favorited activities

NB: the same endpoint is used to favorite and unfavorite an activity item. In case the activity is already favorited, it will remove this activity item from favorite activities.

Arguments

Name Description
id A unique numeric ID for the activity item. Required.
JSON data type: integer.

Definition

POST /buddypress/v2/activity/<id>/favorite

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/activity/17/favorite', {
	method: 'POST',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

[^1]: This property is only available if the WordPress discussion settings allow avatars.

Components REST API routes

BuddyPress chose a modular approach using components to organize its features. Two components are loaded by default (eg: BuddyPress Core and Community Members) while the majority are optional. BuddyPress comes with 8 built-in optional components (Account Settings, Activity Streams, Extended Profiles, Friend connections, Notifications, Private messaging, User groups and Site Tracking).

[!IMPORTANT] It’s important to note there can be more than one optional component from BuddyPress plugins installed on the website: these plugins can use the BuddyPress Component API to incorporate the lists of active or inactive components.

Schema

The schema defines all the fields that exist for BuddyPress components.

Property Description
name Key name of the component.
JSON data type: string.
Context: view, edit.
is_active Whether the component is active or not.
JSON data type: boolean.
Default: false.
Context: view, edit.
status Whether the component is active or inactive.
JSON data type: string.
Context: view, edit.
One of: active, inactive.
title Title of the component.
JSON data type: string.
Context: view, edit.
description Description of the component.
JSON data type: string.
Context: view, edit.
features Information about active features for the component.
JSON data type: object | null.
Default: null.
Context: view, edit.

List the BuddyPress components

Arguments

Name Description
context Scope under which the request is made; determines fields present in response.
JSON data type: string.
Default: view.
One of: view, edit.
page Current page of the collection.
JSON data type: integer.
Default: 1.
per_page Maximum number of components to be returned in result set.
JSON data type: integer.
Default: 10.
search Limit results to those matching a string.
JSON data type: string.
status Limit result set to components with a specific status.
JSON data type: string.
Default: all.
One of: all, active, inactive.
type Information about active features for the component.
JSON data type: string.
Default: all.
One of: all, optional, retired, required.

Definition

GET /buddypress/v2/components

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/components?context=edit&status=active', {
	method: 'GET',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.table( data );
} );

JSON Response

Activate or Deactivate a BuddyPress component

Arguments

Name Description
name Key name of the component. Required.
JSON data type: string.
action Whether to activate or deactivate the component. Required.
JSON data type: string.
One of: activate, deactivate.

Definition

PUT /buddypress/v2/components

Example of use

[!WARNING] The requestHeaders needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/components', {
	method: 'PUT',
	headers: requestHeaders,
	body: JSON.stringify( { name: 'groups', action: 'activate' } ),
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

User Groups REST API routes

The Groups component allow your users to organize themselves into specific public, private or hidden sections of your community site with separate activity streams and member listings.

[!IMPORTANT] The User Groups component is an optional one. This means the buddypress/v2/groups/* endpoints will only be available if the component is active on the community site.

Schema

The schema defines all the fields that exist for a Groups component single item.

Property Description
id A unique numeric ID for the Groups single item.
JSON data type: integer.
Read only.
Context: embed, view, edit.
creator_id The ID of the user who created the Groups single item.
JSON data type: integer.
Default: the ID of the logged in member.
Context: embed, view, edit.
name The name of the Groups single item.
JSON data type: string.
Required: true.
Context: embed, view, edit.
slug The URL-friendly slug for the Groups single item.
JSON data type: string.
Context: embed, view, edit.
link The permalink to the Groups single item on the site.
JSON data type: string, format: URI.
Read only.
Context: embed, view, edit.
description The description of the Groups single item.
JSON data type: object (properties: raw, rendered ).
Required: true.
Context: embed, view, edit.
status The status of the Groups single item (e.g.: private).
JSON data type: string.
One of: public, private, hidden.
Context: embed, view, edit.
enable_forum Whether the Group has a forum enabled or not[^1].
JSON data type: boolean.
Context: embed, view, edit.
parent_id ID of the parent Groups single item[^2].
JSON data type: integer.
Context: embed, view, edit.
date_created The date the Groups single item was created, in the site's timezone.
JSON data type: string | null, format: date-time.
Read only.
Context: embed, view, edit.
date_created_gmt The date the Groups single item was created, as GMT.
JSON data type: string | null, format: date-time.
Read only.
Context: view, edit.
created_since Time elapsed since the Groups single item was created, in the site's timezone.
JSON data type: string.
Default: ''.
Read only.
Context: embed, view, edit.
types The BP Group type(s) assigned to the Groups single item. See this documentation page for more information about Group Types.
JSON data type: array.
Read only.
Context: embed, view, edit.
admins The list of Groups single item administrators.
JSON data type: array.
Read only.
Context: edit.
mods The list of Groups single item moderators.
JSON data type: array.
Read only.
Context: edit.
total_member_count Count of all Group members.
JSON data type: integer.
Read only.
Context: embed, view, edit.
last_activity The date the Groups single item was last active, in the site's timezone.
JSON data type: string | null, format: date-time.
Read only.
Context: embed, view, edit.
last_activity_gmt The date the Groups single item was last active, as GMT.
JSON data type: string | null, format: date-time.
Read only.
Context: view, edit.
last_activity_diff Time elapsed since the Groups single item was last active.
JSON data type: string.
Default: ''.
Read only.
Context: embed, view, edit.
avatar_urls[^3] Avatar URLs for the Groups single item (Full & Thumb sizes).
JSON data type: object (properties: full, and thumb).
Read only.
Context: embed, view, edit.

List User Groups

Arguments

Name Description
context Scope under which the request is made; determines fields present in response.
JSON data type: string.
Default: view.
One of: view, embed, edit.
page Current page of the collection.
JSON data type: integer.
Default: 1.
per_page Maximum number of groups single items to be returned in result set.
JSON data type: integer.
Default: 10.
search Limit results to those matching a string.
JSON data type: string.
exclude Ensure result set excludes Groups with specific IDs
JSON data type: array.
Default: [].
include Ensure result set includes Groups with specific IDs.
JSON data type: array.
Default: [].
type Shorthand for certain orderby/order combinations
JSON data type: string.
Default: active.
One of: active, newest, alphabetical, random, popular.
order Order sort attribute ascending or descending.
JSON data type: string.
Default: desc.
One of: desc, asc.
orderby Order Groups by which attribute.
JSON data type: string.
Default: date_created.
One of: date_created, last_activity, total_member_count, name, random.
user_id Limit result set to Groups single items that this user (ID) is a member of.
JSON data type: integer.
Default: 0.
status Group statuses to limit results to.
JSON data type: array.
Default: [].
One or more of: public, private, hidden.
parent_id Get Groups single items that are children of the specified Group(s) IDs[^2].
JSON data type: array.
Default: [].
meta Get Groups based on their meta data information.
JSON data type: array.
Default: [].
group_type Limit results set to a certain Group type. See this documentation page for more information about Group Types.
JSON data type: string.
Default: ''.
One of: the registered Group types on the site.
enable_forum Whether the group has a forum enabled or not.
JSON data type: boolean.
Default: false.
populate_extras Whether to fetch extra BP data about the returned groups.
JSON data type: boolean.
Default: false.
show_hidden Whether results should include hidden Groups.
JSON data type: boolean.
Default: false.

Definition

GET /buddypress/v2/groups

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/groups?context=view&populate_extras=true', {
	method: 'GET',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.table( data );
} );

JSON Response

Create a User Group

Logged in users can create Groups single items, unless the Site's administrator has disabled their capacity from BuddyPress settings.

Arguments

Name Description
creator_id The ID of the user who created the Group.
JSON data type: integer.
Default: the ID of the logged in member.
name The name of the Group.
JSON data type: string.
Required.
description The description of the Group.
JSON data type: string.
Required.
slug The URL-friendly slug for the Group.
JSON data type: string.
status The status of the Group.
JSON data type: string.
One of: public, private, hidden.
Default: public.
types The BP Group type(s) assigned to the Groups single item. See this documentation page for more information about Group Types. To assign more than one type, use a comma separated list of types.
JSON data type: string.
One of: the registered group types.
parent_id ID of the parent Group[^2].
JSON data type: integer.
enable_forum Whether the Group has a forum enabled or not.
JSON data type: boolean.

Definition

POST /buddypress/v2/groups

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/groups', {
	method: 'POST',
	headers: requestHeaders,
	body: JSON.stringify(
		{
			name: 'Bapuus',
			description: 'bapuu is the BuddyPress wapuu',
		}
	),
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Retrieve a specific User Group

Arguments

Name Description
id A unique numeric ID for the Groups single item. Required.
JSON data type: integer.
context Scope under which the request is made; determines fields present in response.
JSON data type: string.
Default: view.
One of: view, embed, edit.
populate_extras Whether to fetch extra BP data about the returned groups.
JSON data type: boolean.
Default: false.

Definition

GET /buddypress/v2/groups/<id>

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/groups/4', {
	method: 'GET',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Update a specific User Group

Arguments

Name Description
id A unique numeric ID for the Groups single item. Required.
JSON data type: integer.
creator_id The ID of the user who created the Group.
JSON data type: integer.
Default: the ID of the logged in member.
name The name of the Group.
JSON data type: string.
Required.
description The description of the Group.
JSON data type: string.
Required.
slug The URL-friendly slug for the Group.
JSON data type: string.
status The status of the Group.
JSON data type: string.
One of: public, private, hidden.
Default: public.
parent_id ID of the parent Group[^2].
JSON data type: integer.
enable_forum Whether the Group has a forum enabled or not.
JSON data type: boolean.
types The BP Group type(s) assigned to the Groups single item. See this documentation page for more information about Group Types. To assign more than one type, use a comma separated list of types.
JSON data type: string.
One of: the registered group types.
append_types Append one or more BP Group type(s) to a group. To append more than one BP Group type, use a comma separated list of BP Group types.
JSON data type: string.
One of: the registered group types.
remove_types Remove one or more BP Group type(s) from a group. To remove more than one BP Group type, use a comma separated list of BP Group types.
JSON data type: string.
One of: the registered group types.

Definition

PUT /buddypress/v2/groups/<id>

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/groups/4', {
	method: 'PUT',
	headers: requestHeaders,
	body: JSON.stringify(
		{
			creator_id: 2,
			status: 'private',
		}
	),
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Delete a specific User group

Arguments

Name Description
id A unique numeric ID for the Groups single item. Required.
JSON data type: integer.

Definition

DELETE /buddypress/v2/groups/<id>

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/groups/4', {
	method: 'DELETE',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

List the User Groups of the logged in member

Arguments

Name Description
context Scope under which the request is made; determines fields present in response.
JSON data type: string.
Default: view.
One of: view, embed, edit.
max The maximum amount of groups the user is member of to return. Defaults to all groups.
JSON data type: integer.
Default: 0.

Definition

GET /buddypress/v2/groups/me

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/groups/me', {
	method: 'GET',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

[^1]: the enable_forum is used by the bbPress plugin to inform the corresponding group has a forum associated to it. [^2]: the parent_id field is not used by BuddyPress internally to provide a groups hierarchy feature leaving this part to BuddyPress Add-ons. See changeset 11095. [^3]: This property is only available if the WordPress discussion settings allow avatars and the Site Administrator allowed group administrators to upload profile photos for groups.

Members REST API routes

The BuddyPress Members REST controller extends the WordPress Users one to include specific BuddyPress data such as profile fields data[^1] and use the BP_User_Query instead of the WP_User_Query to fetch the members.

Schema

The schema defines all the fields that exist for a member object.

Property Description
id Unique identifier for the member.
JSON data type: integer.
Read only.
Context: embed, view, edit.
name Display name for the member.
JSON data type: string.
Context: embed, view, edit.
mention_name The name used for that user in @-mentions.
JSON data type: string.
Context: embed, view, edit.
link Profile URL of the member.
JSON data type: string, format: URI.
Read only.
Context: embed, view, edit.
user_login An alphanumeric identifier for the member.
JSON data type: string.
Context: embed, view, edit.
member_types Member types associated with the member. See this documentation page for more information.
JSON data type: array.
Read only.
Context: embed, view, edit.
registered_date Registration date for the member.
JSON data type: string | null, format: date-time.
Read only.
Context: edit.
registered_date_gmt The date the member was registered, as GMT.
JSON data type: string | null, format: date-time.
Read only.
Context: edit.
registered_since Elapsed time since the member registered.
JSON data type: string.
Read only.
Context: view, edit.
password Password for the member (never included).
JSON data type: string.
Context: none.
roles Roles assigned to the member.
JSON data type: array.
Context: edit.
capabilities All capabilities assigned to the member.
JSON data type: object.
Read only.
Context: edit.
capabilities Any extra capabilities assigned to the user.
JSON data type: object.
Read only.
Context: edit.
xprofile[^2] Member xProfile groups and its fields.
JSON data type: array.
Read only.
Context: view, edit.
friendship_status[^3] Whether the logged in user has a friendship relationship with the fetched user.
JSON data type: boolean.
Read only.
Context: view, edit.
friendship_status_slug[^3] Slug of the friendship relationship status the logged in user has with the fetched user.
JSON data type: string.
Read only.
One of: is_friend, not_friends, pending, awaiting_response.
Context: view, edit.
total_friend_count[^3] Total number of friends for the member.
JSON data type: integer.
Read only.
Context: view, edit.
last_activity Last date the member was active on the site.
JSON data type: object (properties: timediff, date and date_gmt).
Read only.
Context: view, edit.
latest_update[^4] The content of the latest activity posted by the member.
JSON data type: object (properties: id, raw and rendered).
Read only.
Context: view, edit.
avatar_urls[^5] Avatar URLs for the member (Full & Thumb sizes).
JSON data type: object (properties: full, and thumb).
Read only.
Context: embed, view, edit.

List Members

Arguments

Name Description
context Scope under which the request is made; determines fields present in response.
JSON data type: string.
Default: view.
One of: view, embed, edit.
page Current page of the collection.
JSON data type: integer.
Default: 1.
per_page Maximum number of members to be returned in result set.
JSON data type: integer.
Default: 10.
search Limit results to those matching a string.
JSON data type: string.
exclude Ensure result set excludes specific IDs.
JSON data type: array.
Default: [].
include Ensure result set includes specific IDs.
JSON data type: array.
Default: [].
type Shorthand for certain orderby/order combinations.
JSON data type: string.
Default: newest.
One of: active, newest, alphabetical, random, online, popular.
user_id Limit results to friends of a user.
JSON data type: integer.
Default: 0.
user_ids Pass IDs of users to limit result set.
JSON data type: array.
Default: [].
populate_extras Whether to fetch extra BP data about the returned members.
JSON data type: boolean.
Default: false.
member_type Limit results set to certain type(s). See this documentation page for more information.
JSON data type: array.
Default: [].
xprofile Limit results set to a certain xProfile field.
JSON data type: array.
Default: [].

Definition

GET /buddypress/v2/members

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/members?context=view&type=active', {
	method: 'GET',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.table( data );
} );

JSON Response

Create a member

Only users having the create_users WordPress capability can create a new member.

Arguments

Name Description
user_login An alphanumeric identifier for the member. Required.
JSON data type: string.
password Password for the member. Required.
JSON data type: string.
email The email address for the member. Required.
JSON data type: string.
name Display name for the member.
JSON data type: string.
roles Roles assigned to the member.
JSON data type: array.
member_type A comma separated list of Member Types to set for the member. See this documentation page for more information.
JSON data type: string.

Definition

POST /buddypress/v2/members

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/members', {
	method: 'POST',
	headers: requestHeaders,
	body: JSON.stringify(
		{
			'user_login': 'bapuu',
			password: 'neverUseWe@kPassW0rd!',
			email: 'bapuu@buddypress.org',
			name: 'Bapuu',
		}
	),
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Retrieve a specific member

Arguments

Name Description
id Unique identifier for the member. Required.
JSON data type: integer.
context Scope under which the request is made; determines fields present in response.
JSON data type: string.
Default: view.
One of: view, embed, edit.
populate_extras Whether to fetch extra BP data about the returned member.
JSON data type: boolean.
Default: false.

Definition

GET /buddypress/v2/members/<id>

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/members/2?populate_extras=true', {
	method: 'GET',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Update a specific member

Arguments

Name Description
id Unique identifier for the user. Required.
JSON data type: integer.
name Display name for the member.
JSON data type: string.
roles Roles assigned to the member.
JSON data type: array.
member_type A comma separated list of Member Types to set for the member. See this documentation page for more information.
JSON data type: string.

Definition

PUT /buddypress/v2/members/<id>

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/members/2', {
	method: 'PUT',
	headers: requestHeaders,
	body: JSON.stringify( { name: 'Bapuu The BP Wapuu' } ),
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Delete a specific member

Arguments

Name Description
id Unique identifier for the user. Required.
JSON data type: integer.
force Required to be true, as members do not support trashing. Required.
JSON data type: boolean.
Default: false.
reassign Reassign the deleted member’s posts and links to this user ID. Required.
JSON data type: integer.

Definition

DELETE /buddypress/v2/members/<id>

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/members/2', {
	method: 'DELETE',
	headers: requestHeaders,
	body: JSON.stringify(
		{
			force: true,
			reassign: 1,
		}
	),
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Retrieve the logged in member

Arguments

Name Description
context Scope under which the request is made; determines fields present in response.
JSON data type: string.
Default: view.
One of: view, embed, edit.
populate_extras Whether to fetch extra BP data about the returned member.
JSON data type: boolean.
Default: false.

Definition

GET /buddypress/v2/members/me

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/members/me', {
	method: 'GET',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Update the logged in member

To update roles, the logged in member must have the_ promote_user capability.

Arguments

Name Description
name Display name for the member.
JSON data type: string.
roles Roles assigned to the member.
JSON data type: array.
member_type A comma separated list of Member Types to set for the member. See this documentation page for more information.
JSON data type: string.

Definition

PUT /buddypress/v2/members/me

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/members/me', {
	method: 'PUT',
	headers: requestHeaders,
	body: JSON.stringify( { name: 'Admin Istrator' } ),
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Delete the logged in member

Arguments

Name Description
force Required to be true, as members do not support trashing. Required.
JSON data type: boolean.
Default: false.
reassign Reassign the deleted member’s posts and links to this user ID. Required.
JSON data type: integer.

Definition

DELETE /buddypress/v2/members/me

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/members/me', {
	method: 'DELETE',
	headers: requestHeaders,
	body: JSON.stringify(
		{
			force: true,
			reassign: 1,
		}
	),
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

[^1]: the eXtended Profiles component needs to be active on the website to make these profile fields available into Members REST requests. [^2]: data is only fetched if the eXtended Profiles component is active. [^3]: data is only fetched if the Friends component is active. [^4]: data is only fetched if the Activity component is active. [^5]: This property is only available if the WordPress discussion settings allow avatars.

Private Messaging REST API routes

The Private Messaging component allow your users to talk to each other directly and in private. It’s not just limited to one-on-one discussions, private conversations can involve any number of members.

[!IMPORTANT] The Private Messaging component is an optional one. This means the following endpoints will only be available if the component is active on the community site.

Schema

The schema defines all the fields that exist for a Thread object.

Property Description
id A unique numeric ID for the Thread.
JSON data type: integer.
Read only.
Context: view, edit.
message_id The ID of the latest message of the Thread.
JSON data type: integer.
Read only.
Context: view, edit.
last_sender_id The ID of latest sender of the Thread.
JSON data type: integer.
Read only.
Context: view, edit.
subject Title of the latest message of the Thread.
JSON data type: object (properties: raw, rendered ).
Context: view, edit.
excerpt Summary of the latest message of the Thread.
JSON data type: object (properties: raw, rendered ).
Read only.
Context: view, edit.
message Content of the latest message of the Thread.
JSON data type: object (properties: raw, rendered ).
Required.
Context: view, edit.
date Date of the latest message of the Thread, in the site's timezone.
JSON data type: string | null, format: date-time.
Read only.
Context: view, edit.
date_gmt Date of the latest message of the Thread, as GMT.
JSON data type: string | null, format: date-time.
Read only.
Context: view, edit.
unread_count Total count of unread messages into the Thread for the requested user.
JSON data type: integer.
Read only.
Context: view, edit.
sender_ids The list of user IDs for all messages in the Thread.
JSON data type: array.
Read only.
Context: view, edit.
recipients The list of Avatar[^1] URL objects (full, thumb) for the recipient involved into the Thread.
JSON data type: array.
Context: view, edit.
messages List of message objects for the thread.
JSON data type: array.
Read only.
Context: view, edit.
starred_message_ids List of starred message IDs.
JSON data type: array.
Read only.
Context: view, edit.

List Activities

Only logged in users will be able to fetch the threads they are involved in. Administrators can also fetch another user's threads.

Arguments

Name Description
context Scope under which the request is made; determines fields present in response.
JSON data type: string.
Default: view.
One of: view, edit.
page Current page of the threads collection.
JSON data type: integer.
Default: 1.
per_page Maximum number of threads to be returned in result set.
JSON data type: integer.
Default: 10.
Min.: 1, Max.: 100.
messages_page Current page of the messages collection.
JSON data type: integer.
Default: 1.
Min.: 1.
messages_per_page Maximum number of messages to be returned in result set.
JSON data type: integer.
Default: 10.
Min.: 1, Max.: 100.
recipients_page Current page of the recipients collection.
JSON data type: integer.
Default: 1.
Min.: 1.
recipients_per_page Maximum number of recipients to be returned in result set.
JSON data type: integer.
Default: 10.
Min.: 1, Max.: 100.
search Limit results to those matching a string.
JSON data type: string.
type Filter the result by thread status.
JSON data type: string.
One of: read, unread, all.
Default: all.
user_id Limit result set to activity items created by a specific user (ID).
JSON data type: integer.
Default: 0.
box Filter the result by box.
JSON data type: string.
One of: sentbox, inbox, starred.
Default: inbox.

Definition

GET /buddypress/v2/messages

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/messages?context=view&box=sentbox', {
	method: 'GET',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.table( data );
} );

JSON Response

Start a new Messages Thread or reply to an existing one

Only logged in users will be able to init a new thread or reply to an existing one.

Arguments

Name Description
id A unique numeric ID for the Thread. Required when replying to an existing Thread.
JSON data type: integer.
Default: 0.
message Content of the Message to add to the Thread.
JSON data type: string.
Required.
recipients The list of the recipients user IDs of the Message.
JSON data type: array.
Required.
sender_id The user ID of the Message sender.
JSON data type: integer.
Default: the ID of the logged in member.
subject Subject of the Message initializing the Thread.
JSON data type: string.
Default: false.

Definition

POST /buddypress/v2/messages

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/messages', {
	method: 'POST',
	headers: requestHeaders,
	body: JSON.stringify(
		{
			message: 'bapuu is the BuddyPress wapuu',
			recipients: [ 2, 3 ],
		}
	),
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Retrieve a specific Messages Thread

Only logged in users will be able to fetch a thread they are involved in. Administrators can also fetch another user's thread.

Arguments

Name Description
id A unique numeric ID for the Thread. Required.
JSON data type: integer.
messages_page Current page of the messages collection.
JSON data type: integer.
Default: 1.
Min.: 1.
messages_per_page Maximum number of messages to be returned in result set.
JSON data type: integer.
Default: 10.
Min.: 1, Max.: 100.
recipients_page Current page of the recipients collection.
JSON data type: integer.
Default: 1.
Min.: 1.
recipients_per_page Maximum number of recipients to be returned in result set.
JSON data type: integer.
Default: 10.
Min.: 1, Max.: 100.
user_id The user ID to get the thread for.
JSON data type: integer.
order Order sort attribute ascending or descending.
JSON data type: string.
One of: asc, desc.
Default: asc.

Definition

GET /buddypress/v2/messages/<id>

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/messages/2', {
	method: 'GET',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Update metadata about a specific message of the Thread

Arguments

Name Description
id A unique numeric ID for the Thread. Required.
JSON data type: integer.
message_id By default the latest message of the thread will be updated. Specify this message ID to edit another message of the thread.
JSON data type: integer.
read Whether to mark the thread as read.
JSON data type: boolean.
Default: false
unread Whether to mark the thread as unread.
JSON data type: boolean.
Default: false
user_id The user ID to get the thread for.
JSON data type: integer.

Definition

PUT /buddypress/v2/messages/<id>

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/messages/2', {
	method: 'PUT',
	headers: requestHeaders,
	body: JSON.stringify(
		{
			user_id: 2,
			read: true,
		}
	),
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Delete a specific Messages Thread for a user

[!NOTE] When users request to delete a Messages Thread, they are removed from the list of recipients. As soon as the recipients list is empty, the Messages Thread is fully deleted from the database.

Arguments

Name Description
id A unique numeric ID for the activity item. Required.
JSON data type: integer.
user_id The user ID to get the thread for.
JSON data type: integer.

Definition

DELETE /buddypress/v2/messages/<id>

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/messages/2', {
	method: 'DELETE',
	headers: requestHeaders,
	body: JSON.stringify(
		{
			user_id: 2,
		}
	),
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

Star or unstar a specific message of a Thread

Logged in users can star/unstar a specific message of a Thread`.

Arguments

Name Description
id The ID of the a specific message of the Thread. Required.
JSON data type: integer.

[!IMPORTANT] The ID here is not a Messages Thread ID. It’s the ID of a specific message of the Messages Thread.

Definition

PUT /buddypress/v2/messages/starred/<id>

Example of use

[!WARNING] The requestHeaders object needs to be set according to the WordPress REST API nonce. Read more about the REST API authentification.

fetch( '/wp-json/buddypress/v2/messages/starred/2', {
	method: 'POST',
	headers: requestHeaders,
} ).then( ( response ) => {
	return response.json();
} ).then( ( data ) => {
	 console.log( data );
} );

JSON Response

[^1]: This property is only available if the WordPress discussion settings allow avatars.

BP REST API Reference

Just like the WordPress REST API, the BP REST API is organized around REST, and is designed to have predictable, resource-oriented URLs and to use HTTP response codes to indicate API errors. The API uses built-in HTTP features, like HTTP authentication and HTTP verbs, which can be understood by off-the-shelf HTTP clients, and supports cross-origin resource sharing to allow you to interact securely with the API from a client-side web application.

The BP REST API uses JSON exclusively as the request and response format, including error responses.

The BP REST API provides public data accessible to any client anonymously, as well as private data only available after authentication. Once authenticated the BP REST API supports most BuddyPress community actions, allowing you to enhance your plugins with more responsive management tools, or build complex single-page applications.

This API reference provides information on the specific endpoints available through the API, their parameters, and their response data format.

Developer Endpoint Reference

Resource Base Route
Components /buddypress/v2/components
Members /buddypress/v2/members
Member Profile Photo /buddypress/v2/members/<user_id>/avatar
Member Profile Cover /buddypress/v2/members/<user_id>/cover
Member Registration /buddypress/v2/signup
Activity /buddypress/v2/activity
Extended Profile Groups /buddypress/v2/xprofile/groups
Extended Profile Field /buddypress/v2/xprofile/fields
Extended Profile Data /buddypress/v2/xprofile/<field_id>/data/<user_id>
Friends /buddypress/v2/friends
User Groups /buddypress/v2/groups
Group Profile Photo /buddypress/v2/groups/<group_id>/avatar
Group Profile Cover /buddypress/v2/groups/<group_id>/cover
Group Membership /buddypress/v2/groups/<group_id>/members
Group Membership Requests /buddypress/v2/groups/<group_id>/membership-request
Group Invites /buddypress/v2/groups/<group_id>/invites
Private Messaging /buddypress/v2/messages
Screen Notifications /buddypress/v2/notifications
User Blogs /buddypress/v2/blogs
Blog Profile Photo /buddypress/v2/blogs/<id>/avatar

BuddyPress Rewrites Functions

These functions help you build BuddyPress URLs whether your WordPress site is using plain or pretty permalinks.

NB: In version 12.0.0, in order to make sure to support plain permalinks and customizable slugs, many legacy URL functions were deprecated as they were often used to concatenate URL chunks. The full list of these deprecated functions is available inside the plugin's bp-core/deprecated/12.0.php file.

Core functions

bp_rewrites_get_url()

This is the base function used to build BuddyPress URLs. All other BuddyPress URL functions rely on this base function. This function exposes a WordPress filter hook just before returning the built URL. If you need to override all BuddyPress URLs, you can use the bp_rewrites_get_url filter to do so, making sure to get the 2 available filter parameters. The first parameter is the built URL and the second parameter contains all of the arguments that were used to build the URL.

This function was introduced in version 12.0.0

Arguments

bp_rewrites_get_url() accepts only one argument, which is an associative array containing keys referring to the "hierarchy" ofBuddyPress objects. Below is a list of the most commonly available keys.

Array key Type Required Default Description
component_id string No '' The BuddyPress component ID the URL is built for. Possible value is an active BuddyPress components (e.g.: members).
directory_type string No '' BuddyPress members or groups can be organized in types a bit like a taxonomy can organize WordPress posts. Possible values are slugs of the registered group or member types.
single_item string No '' The BP Members, BP Groups, and BP Activity components support individual items such as a member slug, a group slug or an activity ID.
single_item_component string No '' The BP Members component individual pages (the member pages) are organized according to other BuddyPress components to list the displayed member's Activities, Groups or Friends for instance. Possible values are slugs of the active components. Other BP Components such as the Groups or Activity do not use the same URL schema.
single_item_action string No '' The BP Members component uses this parameter to reach sub-pages of a Member's component page. The BP Groups component uses it to reach front-end component pages or the root page of the group’s management area. The BP Activity component uses it to perform an action on the single_item.
single_item_action_variables [string] No [] Used to pass as many additional variables as needed.

Example of use

// Outputs the Members directory URL.
echo bp_rewrites_get_url(
	array(
		'component_id' => 'members',
	)
);

bp_rewrites_get_slug()

This is the function used to get a BuddyPress customized slug. Since 12.0.0, Site Administrators can use the "URLs" BuddyPress settings screen of their WordPress Dashboard to customize the majority of BuddyPress URLs. To retrieve a customized BP URL, you need to use this function to get each customized portion of it. If a customized slug is not found, it will return the value of the default slug.

You need to use bp_rewrites_get_slug() to get the customized slugs for the following parameters of the argument you pass to the bp_rewrites_get_url() function:

NB: when the BP Query Parser is overriden in favor of using the 'legacy' parser (e.g.: when the BP Classic Add-on is in use) the default slug will be immediately returned and 'rewrite' slugs will be ignored.

This function was introduced in version 12.0.0

Arguments

bp_rewrites_get_slug() needs 3 arguments to retrieve the customized slug.

Argument Type Required Default Description
$component_id string Yes '' The BuddyPress component ID the URL is built for. Possible value is the ID of an active BuddyPress component (e.g.: members)
$rewrite_id string Yes '' The BuddyPress component's Rewrite ID element the URL is built for. This Rewrite ID element is a string concatenation using default BuddyPress slugs behind the singular value of a component (e.g.: members => member) separated by underscores. For instance, to get the customized slug for the public profile page of a member, you will use member_profile_public. It's important to note that rewrite IDs do not contain -, if a default BP slug contains one or more, you need to replace it/them with _
$default_slug string Yes '' The BuddyPress component's default slug for the the URL portion. For instance the default slug of the public profile page of a member is public

Example of use

// Init a single member's URL.
$args = array(
	'component_id' => 'members', // The BP Members component ID.
	'single_item'  => 'imath',   // The user slug (stored in $wpdb->users.user_nicename).
);

// Get the customized part of the URL.
$args['single_item_component'] = bp_rewrites_get_slug(
	'members',         // The BP Members component ID.
	'member_activity', // The screen rewrite ID.
	'activity'         // The sub page default slug.
);

// Outputs the customized URL for the Activity page of the member
echo bp_rewrites_get_url( $args );

Members functions

bp_members_get_user_slug()

Thanks to this function you can get the user's slug (which is stored in $wpdb->users.user_nicename). This function exposes a WordPress filter hook just before returning the user's slug. If you need to override a specific user's slug, you can use the bp_members_get_user_slug filter making sure to get the 2 available filter arguments. The first argument is the retrieved user's slug and the second contains the corresponding user ID. bp_members_get_user_url() uses this function to build a user's url.

This function was introduced in version 12.0.0

Arguments

bp_members_get_user_slug() requires one argument, the user ID.

Argument Type Required Defaults Description
$user_id integer Yes 0 The user ID the slug is retrieved for. Possible value is one of the existing users ID (e.g.: 134)

bp_members_get_path_chunks()

This function eases the way to get a list of customized URL slugs for a single Members page. Instead of building an associative array of customized slugs using bp_rewrites_get_slug() on each element of this array, you can use this function to prepare this associative array out of a regular array of BuddyPress default slugs ordered according to their position in the URL (e.g.: to build arguments for this portion of a member URL profile/edit/group/1, you would use array( 'profile', 'edit', 'group', 1 ) ).

This function was introduced in version 12.0.0

Arguments

bp_members_get_path_chunks() requires one argument, an array of path chunks.

Argument Type Required Defaults Description
$chunks [string] Yes [] The array of path chunks to get the associative array expected by bp_members_get_user_url()

Example of use

// The list of path chunks ordered as they would appear in the URL.
$chunks = array( 'profile', 'edit', 'group', 1 );

$member_path_chunks = bp_members_get_path_chunks( $chunks );

// Here's an example of the value returned by bp_members_get_path_chunks( $chunks ).
$path_chunks = array(
	'single_item_component'        => 'profil',   // 'profil' is French for 'profile'.
	'single_item_action'           => 'modifier', // 'modifier' is French for 'edit'.
	'single_item_action_variables' => array(
		'groupe', // 'groupe' is French for 'group'.
		1
	)
);

bp_members_get_user_url()

Use this function to build a single Members' URL. It uses bp_members_get_user_slug() and bp_rewrites_get_url() to do so and exposes a WordPress filter hook just before returning the built URL. If you need to override single Members BuddyPress URLs, you can use the bp_members_get_user_url filter to do so, making sure to get the 4 available filter arguments. The first argument is the built URL, the second & third are the user ID and slug and the last one contains the associative array of path chunks used to build the URL.

This function was introduced in version 12.0.0

Arguments

bp_members_get_user_url() accepts two arguments: the user ID and an associative array of path chunks.

Argument Type Required Defaults Description
$user_id integer Yes 0 The user ID the URL is retrieved for. Possible value is one of the existing users ID (e.g.: 134)
$path_chunks array No '' This associative array of arguments is described below

$path_chunks list of arguments:

Array key Type Required Defaults Description
single_item_component string No '' The BP Members component individual pages (the member pages) are organized according to other BuddyPress components to list the displayed member's Activities, Groups or Friends for instance. Possible values are slugs of the active components.
single_item_action string No '' The BP Members component uses this parameter to reach sub-pages of a Member's component page.
single_item_action_variables [string] No [] Used to pass as many as needed additional variables.

Example of use

$user_id = 134;

// User url is looking like https://site.url/members/user_slug/profile/edit/group/1/.
$user_url = bp_members_get_user_url(
	$user_id,
	bp_members_get_path_chunks( array( 'profile', 'edit', 'group', 1 ) )
);

bp_get_members_directory_permalink() & bp_members_directory_permalink()

The first function,bp_get_members_directory_permalink(), uses bp_rewrites_get_url() to return the Members directory URL. It exposes a WordPress filter hook just before returning the built URL. If you need to override the Members directory URL, you can use the bp_get_members_directory_permalink filter to do so. The second function, bp_members_directory_permalink(), simply echoes the built URL after escaping it.

These functions were introduced in version 1.5.0

bp_get_member_type_directory_permalink() & bp_member_type_directory_permalink()

The first function, bp_get_member_type_directory_permalink(), uses bp_rewrites_get_url() to return the Members directory URL for users having a specific member type (passed as an argument). It exposes a WordPress filter hook just before returning the built URL. If you need to override the URL showing all users having the requested member type, you can use the bp_get_member_type_directory_permalink filter to do so. You'll get the member type object from the second argument of this filter. The second function, bp_member_type_directory_permalink(), echoes the built URL after escaping it.

These functions were introduced in version 2.5.0

Arguments

bp_get_member_type_directory_permalink() accepts one argument: the requested member type ID. If no member type ID is passed, it will try to use the member type previously globalized as the current type during the loading process. If this global is not available, an empty string will be returned instead of the URL to list all users having the requested/global member type.

Argument Type Required Defaults Description
$member_type string No '' The member type ID

bp_get_signup_page() & bp_signup_page()

The first function, bp_get_signup_page(), uses bp_rewrites_get_url() to return the URL to the registration form. It exposes a WordPress filter hook just before returning the built URL. If you need to override this URL, you can use the bp_get_signup_page filter to do so. The second function, bp_signup_page(), echoes the built URL after escaping it.

These functions were introduced in versions 1.1.0 & 1.0.0

bp_get_activation_page() & bp_activation_page()

The first function, bp_get_activation_page(), uses bp_rewrites_get_url() to return the URL to the account activation form. It exposes a WordPress filter hook just before returning the built URL. If you need to override this URL, you can use the bp_get_activation_page filter to do so. The second function, bp_activation_page(), echoes the built URL after escaping it.

These functions were introduced in versions 1.2.0 & 1.0.0

Groups functions

groups_get_slug()

You can get a specific group's slug using this function. You just need to pass it a group ID or a BP_Groups_Group object to do so. If the group ID doesn't match an existing group, you'll get an empty string.

This function was introduced in version 1.0.0

Arguments

groups_get_slug() requires one argument: the group ID or the group object.

Argument Type Required Description
$group integer or BP_Groups_Group Yes The group ID or the group object.

bp_groups_get_path_chunks()

This function eases the way to get a list of customized URL slugs for a single Groups page. Instead of building an associative array of customized slugs using groups_get_slug() on each element of this array, you can use this function to prepare this associative array out of a regular array of BuddyPress default slugs ordered according to their position in the URL (e.g.: to build arguments for this portion of a group URL members, you would use array( 'members' )).

This function was introduced in version 12.0.0

Arguments

bp_groups_get_path_chunks() accepts two arguments: an array of path chunks and the context for the URL. This context informs about whether you need to get the URL of a regular Group page ('read'), the URL of one of the steps of the creation process ('create') or the URL to the front-end's management (in another word: administration) pages of the group ('manage').

NB: for the 'create' & 'manage' contexts, you should always use this function along with the bp_groups_get_create_url() and bp_get_group_manage_url() functions. That's because these two contexts only need the action variables part of the BP URL as they already occupy the action part of the URL for their specific create and admin keyword slugs.

Argument Type Required Defaults Description
$chunks [string] Yes [] The array of path chunks to get the associative array expected by bp_get_group_url(), bp_get_group_manage_url() or bp_groups_get_create_url()
$context string No 'read' The context for the URL. Possible values are 'read', 'create', or 'manage'.
// Example for the "read" context.
$read_path_chunks = bp_groups_get_path_chunks( array( 'members' ), 'read' );

// Here's an example of the value returned by bp_groups_get_path_chunks( array( 'members' ), 'read' ).
$path_chunks = array(
	'single_item_action' => 'membres', // 'membres' is French for 'members'.
);

// NB: use $read_path_chunks along with bp_get_group_url().

// Example for the "manage" context.
$manage_path_chunks = bp_groups_get_path_chunks( array( 'manage-members' ), 'manage' );

// Here's an example of the value returned by bp_groups_get_path_chunks( array( 'manage-members' ), 'manage' ).
$path_chunks = array(
	'single_item_action_variables' => 'gerer-membres', // 'gerer-membres' is French for 'manage-members'.
);

// NB: use $manage_path_chunks along with bp_get_group_manage_url().

// Example for the "create" context.
$create_path_chunks = bp_groups_get_path_chunks( array( 'group-settings' ), 'create' );

// Here's an example of the value returned by bp_groups_get_path_chunks( array( 'group-settings' ), 'create' ).
$path_chunks = array(
	'create_single_item'           => 1,
	'create_single_item_variables' => 'reglages-du-groupe', // 'reglages-du-groupe' is French for 'group-settings'.
);

// NB: use $create_path_chunks along with bp_groups_get_create_url().

bp_get_group_url()

Use this function to build a single Group's URL. It uses groups_get_slug() and bp_rewrites_get_url() to do so and exposes a WordPress filter hook just before returning the built URL. If you need to override single Groups BuddyPress URLs, you can use the bp_get_group_url filter to do so, making sure to get the 4 available filter arguments. The first argument is the built URL, the second and third are the group ID and slug and the last one contains the associative array of path chunks used to build the URL.

This function was introduced in version 12.0.0

Arguments

bp_get_group_url() accepts two arguments: the group ID (or a group object) and an associative array of path chunks.

Argument Type Required Defaults Description
$group integer or BP_Groups_Group Yes 0 The group ID (or the group object) the URL is retrieved for.
$path_chunks array No [] This associative array of arguments is described below

$path_chunks list of arguments:

Array key Type Required Defaults Description
single_item_action string No '' The BP Groups component uses this to reach front-end component pages.
single_item_action_variables [string] No [] Used to pass as many additional variables as needed.

Example of use

$group_id = 12;

// Returned URL is like https://site.url/groups/group_slug/members/.
$user_url = bp_get_group_url(
	$group_id,
	bp_groups_get_path_chunks( array( 'members' ) )
);

bp_get_group_manage_url()

Use this function to get a single Group's front-end admin (management area) URL. It uses bp_get_group() and bp_get_group_url() to do so and exposes a WordPress filter hook just before returning the built URL. If you need to override single Groups front-end admin BuddyPress URLs, you can use the bp_get_group_manage_url filter to do so, making sure to get the 3 available filter arguments. The first argument is the built URL, the second is the group object and the last one contains the associative array of path chunks used to build the URL.

This function was introduced in version 12.0.0

Arguments

bp_get_group_manage_url() accepts two arguments: the group ID, a group slug or a group object, and an associative array of path chunks.

Argument Type Required Defaults Description
$group integer, string or BP_Groups_Group Yes false The group ID, a group slug, or the group object.
$path_chunks array No [] This associative array of arguments is described below

$path_chunks list of arguments:

Array key Type Required Defaults Description
single_item_action_variables [string] No [] Used to pass as many as needed additional variables.

Example of use

$group_id = 12;

// Returned URL is like https://site.url/groups/group_slug/admin/manage-members/.
$user_url = bp_get_group_manage_url(
	$group_id,
	bp_groups_get_path_chunks( array( 'manage-members' ), 'manage' )
);

bp_group_manage_url()

This function echoes the URL built by bp_get_group_manage_url() after escaping it.

This function was introduced in version 12.0.0

Arguments

bp_group_manage_url() accepts two arguments: the group ID, a group slug or a group object, and an associative array of path chunks. This function uses bp_groups_get_path_chunks() to build the associative array expected by bp_group_manage_url().

Argument Type Required Defaults Description
$group integer, string or BP_Groups_Group Yes false The group ID, a group slug, or the group object the URL is retrieved for.
$path_chunks array No [] A list of default BuddyPress slugs.

Example of use

$group_id = 12;

// Returned URL is like https://site.url/groups/group_slug/admin/manage-members/.
bp_group_manage_url(
	$group_id,
	array( 'manage-members' )
);

bp_groups_get_create_url()

This function returns a URL of the group 'create' context. It is used by bp_groups_get_path_chunks() & bp_get_groups_directory_url() to do so.

This function was introduced in version 12.0.0

Arguments

bp_groups_get_create_url() only accepts one argument: the list of action variables to add to the base URL of the 'create' context.

Argument Type Required Defaults Description
$action_variables array No [] A list of default BuddyPress slugs.

Example of use

// Returned URL is like https://site.url/groups/create/step/group-details/.
$create_url = bp_groups_get_create_url( array( 'group-details' ) );

bp_get_groups_directory_url() & bp_groups_directory_url()

The first function, bp_get_groups_directory_url(), uses bp_rewrites_get_url() to return the Groups directory URL. It exposes a WordPress filter hook just before returning the built URL. If you need to override the Groups directory URL, you can use the bp_get_groups_directory_url filter to do so, making sure to get the 2 available filter arguments. The first argument is the built URL, and the second contains the associative array of path chunks used to build the URL. The second function, bp_groups_directory_url(), echoes the built URL after escaping it.

These functions were introduced in version 12.0.0

Arguments

bp_get_groups_directory_url() only accepts one argument: the list of action variables to add to the base URL of the 'create' context.

Argument Type Required Defaults Description
$path_chunks array No [] This associative array of arguments is described below.

$path_chunks list of arguments:

Array keys Type Required Description
create_single_item integer No 1 to generate the URL of the groups 'create' context.
create_single_item_variables [string] No Used to pass as many as needed additional variables for the groups 'create' context.
directory_type string No A group type slug when generating a URL to list all groups of this type is needed.

bp_get_group_type_directory_permalink() & bp_group_type_directory_permalink()

The first function, bp_get_group_type_directory_permalink(), uses bp_get_groups_directory_url() to return the Groups directory URL that lists groups having a specific group type (the type passed in argument). It exposes a WordPress filter hook just before returning the built URL. If you need to override the URL showing all groups having the requested group type, you can use the bp_get_group_type_directory_permalink filter to do so. You'll get the group type object from the second argument of this filter. The second function, bp_group_type_directory_permalink(), echoes the built URL after escaping it.

These functions were introduced in version 2.5.0

Arguments

bp_get_group_type_directory_permalink() accepts one argument: the requested group type ID. If no group type ID is passed, it will try to use the group type previously globalized as the current type during the loading process. If this global is not available, an empty string will be returned instead of the URL to list all groups having the requested/global group type.

Argument Type Required Defaults Description
$group_type string No '' The group type ID

Activity functions

bp_activity_get_permalink()

Use this function to build a single Activity URL. It uses bp_rewrites_get_url() to do so and exposes a WordPress filter hook just before returning the built URL. If you need to override single Activity BuddyPress URLs, you can use the bp_activity_get_permalink filter to do so, making sure to get the 2 available filter arguments. The first argument is the built URL, and the second contains the Activity object.

This function was introduced in version 1.2.0

Arguments

bp_activity_get_permalink() accepts two arguments: the activity ID and optionally the corresponding Activity object.

Argument Type Required Defaults Description
$activity_id integer Yes Null The activity ID the URL is retrieved for.
$activity_obj BP_Activity_Activity No false The activity object the URL is retrieved for

bp_get_activity_directory_permalink() & bp_activity_directory_permalink()

The first function,bp_get_activity_directory_permalink(), uses bp_rewrites_get_url() to return the Activity directory URL. It exposes a WordPress filter hook just before returning the built URL. If you need to override the Activity directory URL, you can use the bp_get_activity_directory_permalink filter to do so. The second function, bp_activity_directory_permalink(), echoes the built URL after escaping it.

This function was introduced in version 1.5.0

Blogs functions

bp_get_blogs_directory_url()

This function uses bp_rewrites_get_url() to return the Blogs directory URL or the URL to create a new Blog. It exposes a WordPress filter hook just before returning the built URL. If you need to override the generated URL, you can use the bp_get_blogs_directory_url filter to do so, making sure to get the 2 available filter arguments. The first argument is the built URL, and the second contains the associative array of path chunks used to build the URL (this array can be useful to help you figure out if the URL to create a new Blog is being generated).

This function was introduced in version 12.0.0

Arguments

bp_get_blogs_directory_url() only accepts one argument: an associative array where the $create_single_item key is set to 1.

Argument Type Required Defaults Description
$path_chunks array No [] The associative array to generate the URL to create a new Blog.

bp_blogs_directory_url()

This function echoes the URL built by bp_get_blogs_directory_url() after escaping it.

This function was introduced in version 12.0.0

BuddyPress URI Globals Functions

These functions provide information about the BuddyPress object being displayed on the front end. Thanks to them, you can programmatically know whether a component's directory, a component's single item, or a specific sub-page is being loaded. These globals are set inside the parse_query() method of the main class of each component when a BuddyPress page loads.

NB: It's important to note that as of version 12.0.0 of BuddyPress, URI globals are only fully set once the bp_parse_query hook has been fired.

URL schemas

To use the BP URI globals the right way, you need to know about the specificities of the BP URL schemas.

Context Schema
Directories site.url/bp_current_component()/
Members single item site.url/members-slug/bp_current_item()/bp_current_component()/bp_current_action()/bp_action_variables()/
Groups single item site.url/groups-slug/bp_current_item()/bp_current_action()/bp_action_variables()/

bp_current_item()

This function was introduced in version 1.0.0. It returns the slug of the single item being viewed. For instance, in site.url/members/alpha/ or site.url/groups/alpha/, bp_current_item() returns alpha.

bp_current_component()

This function was introduced in version 1.0.0. It returns the slug of the component being viewed. For instance, in site.url/members/marie/activity/ or site.url/activity/, bp_current_component() returns activity.

bp_current_action()

This function was introduced in version 1.0.0. It returns the slug of the single item action being viewed. For instance, in site.url/members/marie/activity/mentions, bp_current_action() returns mentions; in site.url/groups/members, bp_current_action() returns members.

bp_action_variables()

This function was introduced in version 1.0.0. It returns a list (array) of the modifiers that follow the single item action slug in the requested URL. For instance, in site.url/members/marie/profile/edit/group/1/, bp_action_variables() returns array( 'group', 1 ).

Theme compatibility features

BuddyPress allows members and groups to upload and manage their Cover Images. This feature enhances the visual appeal of profiles and group pages by providing a customizable background image.

Under the hood it uses the BP Theme Compat Features API which was developed in order to transpose the WP Theme Supports API into the BP Template Packs world.

Theme compatibility feature registration

Just like WordPress is allowing Themes to opt-in for specific functionalities (eg: the custom header) using the add_theme_support() function inside a 'after_setup_theme' hook callback function, you need to wait for the 'bp_after_setup_theme' hook to be fired to register your Theme Compat feature using the bp_set_theme_compat_feature() function.

function set_my_template_pack_features() {
    $template_pack_id = 'my-template-pack-id';
    $feature_args     = array(
        'name'    => 'my_theme_compat_feature',
        'settings' => array(
            'components' => array( 'groups', 'members' ),
        ),
    );

    // Registers the Theme Compat feature into your template pack.
    bp_set_theme_compat_feature( $template_pack_id, $feature_args );
}
add_action( 'bp_after_setup_theme', 'set_my_template_pack_features' );

bp_set_theme_compat_feature()

Use this function to set a Theme compatibility feature.

This function was introduced in version 2.4.0

Arguments

bp_members_get_user_url() accepts two arguments: the Template Pack ID and an associative array of settings.

Argument Type Required Defaults Description
$template_pack_id string Yes '' The Template Pack ID to set the feature for
$feature_args array No [] This associative array of arguments is described below

$feature_args list of arguments:

Array key Type Required Defaults Description
name string No '' The name key of the feature.
settings array No [] Used to pass as many as needed additional variables. NB using a components key with an array listing component IDs that the feature is targeting will link it to these components. In this case you can use bp_is_active( 'members', 'my_theme_compat_feature' ) to check whether you should load the feature's code or not.

Getting the Theme compatibility feature settings

When you need to get the settings of a registered Theme Compat feature, you can use the bp_get_theme_compat_feature() function.

bp_get_theme_compat_feature()

Use this function to get a Theme compatibility feature's settings. It returns false if something went wrong or an object keyed with the settings argument keys containing the settings values.

This function was introduced in version 2.4.0

Arguments

bp_get_theme_compat_feature() accepts one argument: $name.

Argument Type Required Defaults Description
$name string Yes '' the name key of the feature

Get inspired by the Cover Image Theme compatibility feature

Just like this feature does, including extra filters into your code to let advanced users to customize it to better match their Theme can be a good idea.

Below are examples to feed your imagination about how it's possible to modify the BP built-in Cover Image Theme compat feature default settings or completely disable it.

Changing Cover Image Sizes

You can change the default Cover Image sizes by adding a filter in your bp-custom.php file.

/**
 * PS: The Cover Image feature is using the `bp_parse_args()` function. 
 */ 
function my_custom_cover_image_dimensions( $settings = array() ) {
    $settings['width']  = 1400;
    $settings['height'] = 300;

    return $settings;
}
add_filter( 'bp_before_members_cover_image_settings_parse_args', 'my_custom_cover_image_dimensions' );
add_filter( 'bp_before_groups_cover_image_settings_parse_args', 'my_custom_cover_image_dimensions' );

Changing default Cover Image

When users haven't customized their Cover Images yet, this image will be used as a fallback.

/**
 * PS: The Cover Image feature is using the `bp_parse_args()` function. 
 */ 
function my_custom_cover_xprofile_cover_image( $settings = array() ) {
    $settings['default_cover'] = 'https://site.url/to/your/default_cover_image.jpg';

    return $settings;
}
add_filter( 'bp_before_members_cover_image_settings_parse_args', 'my_custom_cover_xprofile_cover_image', 10, 1 );

Disable Cover Images for members or groups

You can disable Cover Images by adding a filter to your bp-custom.php file.

// For members :
add_filter( 'bp_is_members_cover_image_active', '__return_false' );

// For groups :
add_filter( 'bp_is_groups_cover_image_active', '__return_false' );

[!NOTE] Using a bp_is_{$component_id}_{$feature}_active filter is made possible by the fact the Cover Image feature is using the $components feature argument to set it to members & groups.