Advertisement
shayr

Wordpress API calls

Apr 1st, 2023
1,206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.08 KB | None | 0 0
  1. // Define the API endpoint URL
  2. $endpoint_url = 'https://example.com/api/v1/';
  3.  
  4. // Set up the request headers
  5. $request_headers = array(
  6.     'Content-Type' => 'application/json',
  7.     'Authorization' => 'Bearer ' . get_option('api_token')
  8. );
  9.  
  10. // Perform a GET request to retrieve a resource
  11. $response = wp_remote_get($endpoint_url . 'resource/123', array(
  12.     'headers' => $request_headers
  13. ));
  14.  
  15. if (is_wp_error($response)) {
  16.     // Handle the error
  17. } else {
  18.     $resource_data = json_decode(wp_remote_retrieve_body($response));
  19.  
  20.     // Perform a PUT request to update the resource
  21.     $updated_resource_data = array(
  22.         'name' => 'Updated Resource Name',
  23.         'description' => 'Updated resource description'
  24.     );
  25.  
  26.     $response = wp_remote_request($endpoint_url . 'resource/123', array(
  27.         'method' => 'PUT',
  28.         'headers' => $request_headers,
  29.         'body' => json_encode($updated_resource_data)
  30.     ));
  31.  
  32.     if (is_wp_error($response)) {
  33.         // Handle the error
  34.     } else {
  35.         $updated_resource_data = json_decode(wp_remote_retrieve_body($response));
  36.  
  37.         // Perform a POST request to create a new resource
  38.         $new_resource_data = array(
  39.             'name' => 'New Resource Name',
  40.             'description' => 'New resource description'
  41.         );
  42.  
  43.         $response = wp_remote_post($endpoint_url . 'resource', array(
  44.             'headers' => $request_headers,
  45.             'body' => json_encode($new_resource_data)
  46.         ));
  47.  
  48.         if (is_wp_error($response)) {
  49.             // Handle the error
  50.         } else {
  51.             $new_resource_data = json_decode(wp_remote_retrieve_body($response));
  52.  
  53.             // Perform a DELETE request to delete the resource
  54.             $response = wp_remote_request($endpoint_url . 'resource/123', array(
  55.                 'method' => 'DELETE',
  56.                 'headers' => $request_headers
  57.             ));
  58.  
  59.             if (is_wp_error($response)) {
  60.                 // Handle the error
  61.             } else {
  62.                 // Resource successfully deleted
  63.             }
  64.         }
  65.     }
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement