You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BuddyPress:如何仅在首个用户资料组下方添加自定义短代码

解决BuddyPress首个资料组下方仅显示自定义短代码的问题

问题分析

你当前的代码通过硬编码资料组ID=1来判断,但如果首个资料组的实际ID不是1(比如创建顺序调整、ID被占用),就无法触发显示;而移除筛选条件会导致每个资料组下方都重复显示短代码。

可靠解决方案

方案1:利用循环索引判断(推荐)

通过BuddyPress内置的循环计数器,直接判断当前是否为第一个资料组,无需依赖ID:

add_action( 'bp_after_profile_loop_content', 'profile_choices_display' );
function profile_choices_display() {
    global $profile_group_loop;
    
    // 循环索引从0开始,0代表第一个资料组
    if ( 0 === $profile_group_loop->current ) { 
        echo do_shortcode( '[user-profile-choices]' );
    }      
}

方案2:动态获取首个资料组ID

如果需要精准匹配首个资料组的实际ID,可以动态获取当前用户的第一个公开资料组ID:

add_action( 'bp_after_profile_loop_content', 'profile_choices_display' );
function profile_choices_display() {
    // 获取当前显示用户的所有公开资料组
    $profile_groups = bp_get_profile_groups( array(
        'user_id' => bp_displayed_user_id(),
        'visibility' => 'public'
    ) );
    
    if ( ! empty( $profile_groups['groups'] ) ) {
        $first_group_id = $profile_groups['groups'][0]->id;
        
        // 对比当前资料组ID是否为第一个组的ID
        if ( $first_group_id == bp_get_the_profile_group_id() ) { 
            echo do_shortcode( '[user-profile-choices]' );
        }
    }
}

说明

  • 方案1更简洁通用,不受资料组ID变化影响;
  • 方案2适合需要严格匹配首个资料组(而非循环顺序第一个)的场景。

内容的提问来源于stack exchange,提问作者Joe Bloggs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 17:05:21