Discourse Login Redirects to WordPress Dashboard

I took another look at this while it’s fresh in my mind. Adding the following function to my theme’s functions.php file solved the issue for me, but this hasn’t been tested very much.

add_filter( 'mepr-process-login-redirect-url', 'wpdc_login_redirect', 12, 3);
function wpdc_login_redirect( $redirect, $user = false, $is_wp_login_page = false ) {
	$referer = wp_get_referer();
	if ( $referer ) {
		$query_params = [];
		parse_str( parse_url( $referer, PHP_URL_QUERY ), $query_params );
		$sso_referer = ! empty( $query_params['redirect_to'] ) && preg_match( '/^\/\?sso/', $query_params['redirect_to'] );
		if ( $sso_referer ) {

			return home_url( $query_params['redirect_to'] );
		}
	}

	return MeprProductsCtrl::track_and_override_login_redirect_mepr( $redirect, $user, $is_wp_login_page );
}

The function is hooking into the 'mepr-process-login-redirect-url' filter before it is hooked into by MemberPress. It then checks the value of the query params to see if the query was initiated by an SSO request from Discourse. If it was, it redirects the user to the WordPress homepage with the query params intact. This will cause the WP Discourse plugin to complete the SSO request. I think this can still work if your homepage is being protected by MemberPress, but it would be good to confirm that.

If the request was not initiated by Discourse, the static MeprProductsCtrl::track_and_override_login_redirect_mepr is called with the arguments that were passed to the filter.

I’m a little hesitant to recommend adding this code to your production site. If you do try it, make sure that you can remove the code from your server in case it breaks your site. Be sure to test it out will as many user/membership-levels as possible.