根据API响应设置登录用户

时间:2019-06-04 作者:ellen

我有一个外部应用程序,我想重定向到wordpress网站上的页面。该页面需要根据登录用户的不同而有所不同。

应用程序有一个API端点,我可以调用它来获取登录的用户。

基本上,我需要做到以下几点:

1) 加载页面时,将调用API以查看谁已登录。

2) 如果用户不存在,则会创建一个帐户。如果用户确实存在,则会显示其数据。

这可能吗?我试着在谷歌上搜索,但什么也没找到。我想我需要将API调用附加到wp_init 钩子,但不完全确定。

非常感谢您的帮助,如有必要,我可以提供更多信息!

1 个回复
SO网友:Antti Koskinen

init 如果您需要了解当前WP用户的一些信息,因为此时该用户已通过身份验证,那么它可能是执行API调用的好挂钩。您可以使用检查WP用户登录状态is_user_logged_in(), 如果需要。

或者如果你需要重定向,那么template_redirect 也可能是一个可行的钩子。如果您只想更改页面模板,请确定其中的正确模板template_include 滤器

WordPress有自己的HTTP API 您可以使用wp_remote_get(). 但我想cUrl 如果您喜欢使用它,它也会起作用。

如果还需要为WP而不仅仅是API创建新用户,可以使用wp_insert_user() 然后使用wp_signon() 以登录新用户。

下面是一个关于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\' );