Created
July 19, 2023 23:06
-
-
Save vcanales/08bcca2504c97d7f816fede43003246e to your computer and use it in GitHub Desktop.
WP Plugin + GitHub OAuth app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* GitHub OAuth code. | |
* | |
* @package CreateBlockTheme | |
*/ | |
add_action( 'init', 'github_oauth_init' ); | |
function github_oauth_init() { | |
if ( isset( $_GET['github_oauth'] ) && $_GET['github_oauth'] == 'authorize' ) { | |
$client_id = 'GITHUB_CLIENT_ID'; // Replace with your GitHub Client ID | |
$redirect_uri = urlencode( admin_url( 'admin-ajax.php?action=github_oauth_callback' ) ); | |
$url = "https://github.com/login/oauth/authorize?client_id={$client_id}&redirect_uri={$redirect_uri}&scope=user"; | |
wp_redirect( $url ); | |
exit; | |
} | |
} | |
add_action( 'wp_ajax_github_oauth_callback', 'github_oauth_callback' ); | |
add_action( 'wp_ajax_nopriv_github_oauth_callback', 'github_oauth_callback' ); | |
function github_oauth_callback() { | |
if ( isset( $_GET['code'] ) ) { | |
$code = $_GET['code']; | |
$client_id = 'GITHUB_CLIENT_ID'; // Replace with your GitHub Client ID | |
$client_secret = 'GITHUB_CLIENT_SECRET'; // Replace with your GitHub Client Secret | |
$url = 'https://github.com/login/oauth/access_token'; | |
$body = array( | |
'client_id' => $client_id, | |
'client_secret' => $client_secret, | |
'code' => $code, | |
); | |
$options = array( | |
'body' => $body, | |
'headers' => array( | |
'Accept' => 'application/json', | |
), | |
); | |
$response = wp_remote_post( $url, $options ); | |
if ( ! is_wp_error( $response ) ) { | |
$data = json_decode( wp_remote_retrieve_body( $response ), true ); | |
if ( isset( $data['access_token'] ) ) { | |
update_option( 'cbt_theme_manager_github_oauth_access_token', $data['access_token'] ); | |
} | |
} | |
wp_redirect( admin_url( 'site-editor.php?canvas=edit' ) ); | |
} | |
exit; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment