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' );