Halloween Sale 15% off Ends in See the plans
PHP

BuddyPress: Profile Field Shortcode

Adds a [wpide_bp_field name="Location"] shortcode that prints a BuddyPress profile field for the logged-in member, or for the profile being viewed.

Don’t have WPIDE yet? Install it on your site

Code

if ( ! function_exists( 'buddypress' ) ) {
    return;
}

add_shortcode( 'wpide_bp_field', function ( $atts ) {
    $atts    = shortcode_atts( array( 'name' => '', 'user' => 'current', 'fallback' => '' ), $atts, 'wpide_bp_field' );
    $user_id = 'displayed' === $atts['user'] ? bp_displayed_user_id() : bp_loggedin_user_id();

    if ( ! $user_id || '' === $atts['name'] || ! bp_is_active( 'xprofile' ) ) {
        return esc_html( $atts['fallback'] );
    }

    $field_id = xprofile_get_field_id_from_name( $atts['name'] );

    if ( ! $field_id ) {
        return esc_html( $atts['fallback'] );
    }

    // Respect the member's visibility choice when showing someone else's field.
    if ( in_array( (int) $field_id, array_map( 'intval', (array) bp_xprofile_get_hidden_fields_for_user( $user_id, bp_loggedin_user_id() ) ), true ) ) {
        return esc_html( $atts['fallback'] );
    }

    $value = xprofile_get_field_data( $field_id, $user_id, 'comma' );

    return $value ? wp_kses_post( $value ) : esc_html( $atts['fallback'] );
} );

Notes

Add user="displayed" to show the field of the profile being viewed instead of the logged-in member.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.