Create user automatically in Discourse when they sign up in Wordpress?

Other than displaying an error in the console, the embedding method seems to work well.

NOTE: The WP Discourse plugin now has code built into it for creating and syncing users on login when SSO is enabled. It does not automatically log users into Discourse, but for most use cases that shouldn’t be necessary.

Creating a user automatically can be done without embedding the /session/sso URL by adding something like this to your functions.php file. Possibly this could be added as an option to the plugin.

add_action( 'wp_login', 'my_prefix_discourse_login', 10, 2 );
function my_prefix_discourse_login( $user_login, $user ) {
    if ( class_exists( '\WPDiscourse\Utilities\Utilities' ) ) {
        $discourse_options = \WPDiscourse\Utilities\Utilities::get_options();

        if ( ! empty( $discourse_options['enable-sso'] ) && 1 === intval( $discourse_options['enable-sso'] ) ) {
            // Set to where you want to redirect to. To redirect back to WordPress instead of Discourse,
            // you need to enable the Discourse setting 'sso allows all return paths'.
            $redirect     = home_url( '/' );
            $sso_url      = ! empty( $discourse_options['url'] ) ? $discourse_options['url'] . '/session/sso?return_path=' . $redirect : '';
            $query_string = parse_url( wp_get_referer(), PHP_URL_QUERY );
            $query_params   = [];
            parse_str( $query_string, $query_params );
            // Make sure it's the login hasn't been initiated by clicking on a SSO login link.
            $sso_referer = ! empty( $query_params['redirect_to'] ) && preg_match( '/^\/\?sso/', $query_params['redirect_to'] );

            if ( empty( get_user_meta( $user->ID, 'discourse_email_not_verified', true ) ) && ! $sso_referer ) {

                wp_redirect( esc_url( $sso_url ) );

                exit;
            }
        }
    }
8 Likes