0

I'm trying to convert this php code to the wordpress wp_remote_post() format. Thoughts, Ideas, This is NOT my forte, lol.

<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('https://xxxx.yyyyy.zzzzz');
$request->setMethod(HTTP_Request2::METHOD_POST);
$request->setConfig(array(
  'follow_redirects' => TRUE
));
$request->setHeader(array(
  'x-api-key' => 'ppppppppppppppp',
  'Content-Type' => 'application/json'
));
$request->setBody('{\n    "object_type": "Leaderboard",\n    "action": "list",\n    "pagination": {\n       "limit": 5,\n       "order": false\n    },\n    "data": {\n        "username": "[email protected]"\n    }\n}');
try {
  $response = $request->send();
  if ($response->getStatus() == 200) {
    echo $response->getBody();
  }
  else {
    echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
    $response->getReasonPhrase();
  }
}
catch(HTTP_Request2_Exception $e) {
  echo 'Error: ' . $e->getMessage();
}

1 Answer 1

0

Use this code :

$url = 'https://xxxx.yyyyy.zzzzz';

$body_array = array(
                        'object_type' => 'Leaderboard',
                        'action' => 'list',
                        'pagination'    => array(
                                                'limit' => 5,
                                                'order' => false
                                            ),
                        'data'          => array(
                                                'username'  => '[email protected]'
                                            )
                    );



$response = wp_remote_post( $url, array(
        'method'      => 'POST',
        'timeout'     => 45,
        'redirection' => 5,
        'httpversion' => '1.0',
        'blocking'    => true,
        'headers'     => array(
                            'x-api-key' => 'ppppppppppppppp',
                            'Content-Type' => 'application/json'
                        ),
        'body'        => json_encode( $body_array ),
        'cookies'     => array()
    )
);

if ( is_wp_error( $response ) ) {
    $error_message = $response->get_error_message();
    echo "Something went wrong: $error_message";
} else {
    echo 'Response:<pre>';
    print_r( $response );
    echo '</pre>';
}
3
  • WOW, you killed it! You are amazing! This worked! Feb 21, 2020 at 14:21
  • Great. Can you please make this answer correct? So this post will help to other as well :) Feb 21, 2020 at 14:58
  • Hi Can you make this answer correct? if it is work for you? Feb 25, 2020 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.