Created
November 19, 2020 03:43
-
-
Save harisrozak/9a149e2c5011bf8827bded20a84793fe to your computer and use it in GitHub Desktop.
WordPress :: Request to REST API from PHP
This file contains hidden or 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 | |
// send data trough REST API | |
$request = new WP_REST_Request( 'POST', '/wp/v2/custom_post_type' ); | |
$request->set_header( 'content-type', 'application/json' ); | |
$request->set_body( wp_json_encode( $order_data ) ); | |
// get response | |
$response = rest_do_request( $request ); | |
$response_data = $response->get_data(); | |
// if error response | |
if ( $response->is_error() ) { | |
$error = $response->as_error(); | |
$message = $error->get_error_message(); | |
$status = isset( $error_data['status'] ) ? $error_data['status'] : 500; | |
wp_die( sprintf( __( 'An error occurred: %s (%d)', 'xyz' ), $message, $status ), __( 'Error!', 'xyz' ), array( | |
'back_link' => true, | |
) ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment