In this example project, I’ll show how to get shipping rates from the Easy Post API with a custom WordPress endpoint.
To simplify this tutorial, I’m only sending 6 parameters (which is just enough data for Easy Post to return a shipping rate):
- Package Width
- Package Height
- Package Length
- Package Weight
- Zip Code of Sender
- Zip Code of Receiver
Setting Up the JSON Endpoint
First step is to register the route where the JSON data will be served. In this case:
[gist id=”dd15de71e3c563a3e6577acea7fa2d9d” file=”wordpress-easy-post.php” lines=”9-21″]
Displaying the Data
The endpoint route is expecting six pieces of data to be sent as query strings, and it uses that to fetch data from the remote API. If the query strings aren’t present, defaults are used. All the parameters are sanitized to ensure they are integers.
Example URL with query strings:
[gist id=”dd15de71e3c563a3e6577acea7fa2d9d” file=”wordpress-easy-post.php” lines=”23-71″]
Fetching the Data
The function “easy_post_make_request” is what actually requests the data from the external API. The majority of the code here is just arranging the request into an array that the Easy Post API can process.
[gist id=”dd15de71e3c563a3e6577acea7fa2d9d” file=”wordpress-easy-post.php” lines=”73-123″]
Using the Data
When accessing your endpoint, the JSON data fetched from Easy Post should now appear.
Need to pull shipping rates into your site dynamically? Now you’re ready to go.
You can view the full file here.