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.
Thanks so much for this example! I am a newb working with WP and I have a question. Where would this file live? I assume it should be in the cPanel. Please advise. Thanks so much!
You could create a custom plugin or include it from your theme. If you’re including it from your theme, you’d put your custom code in a file in the theme directory, and then include that from functions.php.
I’d recommend working locally while you do development (watch this video to learn how): https://wptheming.com/2018/01/setting-up-a-local-environment/. Then, once you have everything working, upload the new/updated files via SFTP.