Created
September 13, 2019 17:33
-
-
Save brandondove/5b1c663d654b5f08e807c109ebba44eb to your computer and use it in GitHub Desktop.
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 | |
/** | |
* POST to endpoint /wp-json/my-custom-endpoint/v1/save-string | |
* | |
* Send a string and use "Application Passwords" plugin and save to option | |
*/ | |
add_action( 'rest_api_init', 'my_custom_endpoint', 10 ); | |
/** | |
* Registers a custom REST API endpoint. | |
* | |
* @return void | |
*/ | |
function my_custom_endpoint() { | |
register_rest_route( | |
'my-custom-endpoint/v1', | |
'save-string', | |
array( | |
'methods' => 'POST', | |
'callback' => 'my_custom_endpoint_callback', | |
) | |
); | |
} | |
/** | |
* The callback for your custom endpoint. | |
* | |
* @param WP_REST_Request $request The REST request object. | |
* @return void | |
*/ | |
function my_custom_endpoint_callback( $request ) { | |
/** | |
* These are headers that your | |
* microservice's request should contain | |
* | |
* The password should be set using | |
* the "Application Passwords" plugin | |
* https://wordpress.org/plugins/application-passwords/ | |
*/ | |
$user_login = $request->get_header( 'user_login' ); | |
$user_password = $request->get_header( 'user_password' ); | |
$user = wp_signon( | |
array( | |
'user_login' => $user_login, | |
'user_password' => $user_password, | |
'remember' => false, | |
) | |
); | |
if ( is_wp_error( $user ) ) { | |
wp_send_json_error( 'User must be authenticated', 401 ); | |
return; | |
} | |
// This is where you would do something with the request. | |
$params = $request->get_body_params(); | |
if ( ! isset( $params['string'] ) ) { | |
wp_send_json_error( 'Must include string param.', 400 ); | |
return; | |
} | |
// Update an option. You can do anything here. | |
$string = sanitize_text_field( $params['string'] ); | |
update_option( 'test-string', $string ); | |
// Send JSON success back to the microservice. | |
wp_send_json_success( 'ok' ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment