Search code examples
phpwordpressurl-rewritingbuddypress

How to create a new rewrite rule for an buddy press profile page


I have an existing buddy press user profile link: e.g. https://example.com/members/joseph-bada

I need to make https://example.com/members/joseph-b an exact duplicate of it.

this my code simplified version:

add_filter('wp', 'custom_rewrite_rule');
function custom_rewrite_rule() {
    global $wp_query, $wp_rewrite;
    $slug = $wp_query->query_vars['name'];
    if($slug==='joseph-bada') {
        add_rewrite_rule('^members/joseph-b/?', 'members/joseph-bada', 'top');
        $wp_rewrite->flush_rules();
    }
}

but if i browse https://example.com/members/joseph-b - i get 404 error

UPDATE: even after adding this in functions.php

add_action('init', 'custom_test');
function custom_test() {
    global $wp_rewrite;
    add_rewrite_rule('^members/joseph-b', 'members/joseph-bada', 'top');
    $wp_rewrite->flush_rules();
}

https://example.com/members/joseph-b is still 404

can someone please point out what im missing?

UPDATE: i learned that https://example.com/index.php?bbp_user=joseph-bada&edit=1 leads to https://example.com/members/joseph-bada

so now i tried this:

add_action('init', 'custom_test');
function custom_test() {
    global $wp_rewrite;
    add_rewrite_rule('^members/joseph-b', 'https://example.com/index.php?bbp_user=joseph-bada&edit=1', 'top');
    $wp_rewrite->flush_rules();
}

still no avail 404 though..


Solution

  • i gave up using add_rewrite_rule wordpress functionality.. instead, i studied buddypress plugin and how it works.. i discovered the following filters:

    function custom_bp_domain_filter($domain, $user_id) {
        $change_slug = is_joseph_bada_user_id($user_id);
        if ($change_slug) {
            $domain = trailingslashit(bp_get_root_domain() . '/' . 'members/joseph-b');
        }
        return $domain;
    }
    
    add_filter('bp_core_get_user_domain', 'custom_bp_domain_filter', 10, 2);
    

    this part above is a filter wherein im gonna check if the user id being displayed belongs to members/joseph-bada. if it is, change it to members/joseph-b

    function custom_bp_after_slug_filter($after_member_slug) {
    
        if ($after_member_slug==='joseph-b') {
            $after_member_slug = 'joseph-bada';
        }
        return $after_member_slug;
    }
    
    add_filter('bp_core_set_uri_globals_member_slug', 'custom_bp_after_slug_filter');
    

    this above part determines if the URI is now members/joseph-b.. we dont have a user with that, instead it is 'joseph-bada'

    the returned value here is the user to be displayed so we need to return 'joseph-bada' if the param value is 'joseph-b'

    when members/joseph-b is browsed.. it will display the profile of members/joseph-bada