bp_redirect_canonical()

Canonicalize BuddyPress URLs.

Description

This function ensures that requests for BuddyPress content are always redirected to their canonical versions. Canonical versions are always trailingslashed, and are typically the most general possible versions of the URL – eg, example.com/groups/mygroup/ instead of example.com/groups/mygroup/home/.

See also

Source

File: bp-core/bp-core-catchuri.php

function bp_redirect_canonical() {

	/**
	 * Filters whether or not to do canonical redirects on BuddyPress URLs.
	 *
	 * @since BuddyPress 1.6.0
	 *
	 * @param bool $value Whether or not to do canonical redirects. Default true.
	 */
	if ( !bp_is_blog_page() && apply_filters( 'bp_do_redirect_canonical', true ) ) {
		// If this is a POST request, don't do a canonical redirect.
		// This is for backward compatibility with plugins that submit form requests to
		// non-canonical URLs. Plugin authors should do their best to use canonical URLs in
		// their form actions.
		if ( !empty( $_POST ) ) {
			return;
		}

		// Build the URL in the address bar.
		$requested_url  = bp_get_requested_url();

		// Stash query args.
		$url_stack      = explode( '?', $requested_url );
		$req_url_clean  = $url_stack[0];
		$query_args     = isset( $url_stack[1] ) ? $url_stack[1] : '';

		$canonical_url  = bp_get_canonical_url();

		// Only redirect if we've assembled a URL different from the request.
		if ( $canonical_url !== $req_url_clean ) {

			$bp = buddypress();

			// Template messages have been deleted from the cookie by this point, so
			// they must be readded before redirecting.
			if ( isset( $bp->template_message ) ) {
				$message      = stripslashes( $bp->template_message );
				$message_type = isset( $bp->template_message_type ) ? $bp->template_message_type : 'success';

				bp_core_add_message( $message, $message_type );
			}

			if ( !empty( $query_args ) ) {
				$canonical_url .= '?' . $query_args;
			}

			bp_core_redirect( $canonical_url, 301 );
		}
	}
}

Changelog

Changelog
Version Description
BuddyPress 1.6.0 Introduced.

Questions?

We're always happy to help with code or other questions you might have! Search our developer docs, contact support, or connect with our sales team.