0

I have an external application that I want to redirect to a page on a wordpress site. The page needs to be different based on who is logged in.

The application has an API endpoint which I can call to get the logged in user.

Basically, I need the following to happen:

1) When the page loads, the API gets called to see who is logged in.

2) If the user does not exist, an account is created. If the user does exist, their data is displayed.

Is this possible to do? I tried googling it and found nothing. I'm thinking I will want the API call attached to the wp_init hook but not totally sure.

Any help is appreciated and I can provide more information if necessary!

0

init is probably a good hook to do the API call, if you need know somehting about the current WP user as the user is authenticated by that time. You can check the WP user login status with is_user_logged_in(), if needed.

Or if you need to do some redirecting, then template_redirect could also be a viable hook. If you just want to change the page template, then determine the correct template inside template_include filter.

WordPress has its own HTTP API that you could perhaps use to make the API call by using wp_remote_get(). But I guess cUrl will work as well, if you prefer to use it.

If you also need to create a new user to WP and not just to your API, you can use wp_insert_user() and then use wp_signon() to log the new user in.

Here's a rough example regarding wp_remote_get(),

function check_login_status() {

  // if relevant to check wp login status
  // if ( is_user_logged_in() ) {
  //   // do something
  // }

  $api_url = 'http://api.isuserloggedin.com';
  // defaults shown
  $api_request_args = array(
    // 'timeout'     => 5,
    // 'redirection' => 5,
    // 'httpversion' => '1.0',
    // 'user-agent'  => 'WordPress/' . $wp_version . '; ' . home_url(),
    // 'blocking'    => true,
    // 'headers'     => array(),
    // 'cookies'     => array(),
    // 'body'        => null,
    // 'compress'    => false,
    // 'decompress'  => true,
    // 'sslverify'   => true,
    // 'stream'      => false,
    // 'filename'    => null
  );
  $api_request = wp_remote_get( $api_url, $api_request_args );

  if ( ! is_wp_error( $api_request ) ) {
    $response = wp_remote_retrieve_body( $api_request );
    // if needed, decode the $response
    // $response = json_decode( $response );

    // do something with the $response

  } else {
    // api call failed    
  }

}
add_action( 'init', 'check_login_status' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.