Using BuddyPress for Social Networks

Creating Custom URL’s in BuddyPress

Creating Custom URL’s with BuddyPress

Sometimes the default URL provided by BuddyPress is not quite what is required. Recently I had a requirement where the given url was not quite right.

I was asked to change www.examplesite.com/members/username/projects to www.example.com/projects/username for a particular use case.

For my solution I was able to use the BuddyPress CatchURI method in order to cantch and repurpose the requested URL in order to support the new format.

It’s important to note that the BP catch URI process triggers prior to WordPresses own permalink rewrites, to to make changes to BP URL’s it’s BP that needs to be told to expect the new format.

BP’s CatchURI process includes a filter – bp_url which passes the requested url prior to BP carrying out it’s own processing.

Here’s my code:

function bp_projects_rewrite_bp_uri($path) {
    if(strpos($path, 'projects/') === 1 && strlen( $path) > 5 ) {

        //Find the position of the second '/' and add one to fix the start of the username.
        $members_start_pos = strpos( $path, '/', 2 ) +1;

        //Find the end point of the username
        $members_end_pos = strpos( $path, '/', $members_start_pos );

        //Strip the username out of the input URL
        $username = substr( $path, $members_start_pos, $members_end_pos - $members_start_pos );

        //Return the reconstructed URL, which BP will accet as a valid page.
        return 'members/'.$username.'/card/';
    }

    return $path;
}

add_filter('bp_uri', 'bp_projects_rewrite_bp_uri');

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.