Skip to content

Instantly share code, notes, and snippets.

@harisrozak
Created November 19, 2020 03:43
Show Gist options
  • Save harisrozak/9a149e2c5011bf8827bded20a84793fe to your computer and use it in GitHub Desktop.
Save harisrozak/9a149e2c5011bf8827bded20a84793fe to your computer and use it in GitHub Desktop.
WordPress :: Request to REST API from PHP
<?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