Skip to content

Instantly share code, notes, and snippets.

@imath
Created Feb 6, 2015
Embed
What would you like to do?
BuddyPress member types : display the type near each user in the members loop (requires BuddyPress 2.2)
<?php
/**
* Using BuddyPress Member types API
*
* see codex: https://codex.buddypress.org/developer/member-types/
*
* Required config:
* - WordPress 4.1
* - BuddyPress 2.2
*
* License: GNU/GPL 2
* Author: imath
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Register member types.
*
* From the wp-admin/extended profile
* it will be possible to set the user's member type
*/
function using_mt_register_member_types() {
bp_register_member_type( 'student', array(
'labels' => array(
'name' => __( 'Students', 'using-mt' ),
'singular_name' => __( 'Student', 'using-mt' ),
),
) );
bp_register_member_type( 'teacher', array(
'labels' => array(
'name' => __( 'Teachers', 'using-mt' ),
'singular_name' => __( 'Teacher', 'using-mt' ),
),
) );
}
add_action( 'bp_init', 'using_mt_register_member_types' );
/**
* Get the singular name out of of member type's name or array of names
*/
function using_mt_get_member_type_singular_name( $name = '' ) {
if ( empty( $name ) ) {
return false;
}
$output = '';
if ( is_array( $name ) ) {
$member_types_objects = bp_get_member_types( array(), 'objects' );
$output_array = array();
foreach ( $name as $name_type ) {
if ( empty( $member_types_objects[ $name_type ]->labels['singular_name'] ) ) {
continue;
}
$output_array[] = $member_types_objects[ $name_type ]->labels['singular_name'];
}
$output = join( ', ', $output_array );
} else {
$member_type_object = bp_get_member_type_object( $name );
if ( ! empty( $member_type_object->labels['singular_name'] ) ) {
$output = $member_type_object->labels['singular_name'];
}
}
return $output;
}
/**
* Display in loop
*
* If a member has more than one member types, they will be comma separated
*/
function using_mt_in_members_loop() {
$member_type = bp_get_member_type( bp_get_member_user_id(), false );
echo esc_html( using_mt_get_member_type_singular_name( $member_type ) );
}
add_action( 'bp_directory_members_item', 'using_mt_in_members_loop' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment