Building a WordPress API Request

In an effort to put more content on this blog, i’ve decided to try and take some simplified quick and dirty versions of code i’ve written or concepts that i’ve re-used in various scenarios. Below is an example function, with commenting, of what a starter function to make a server side request to a JSON api might look like!

function api_request($endpoint='', $param=array(), $args=array(), $lifespan=HOUR_IN_SECONDS){
    $apikey = 'your api key here'; // maybe get from the db
    $base   = 'http://my.api.base/api'; // maybe use a const in a class

    // ensure we have what we need
    if ( !$apikey ) return new WP_Error('request', 'no api key', 'APIKEY');

    // prepare url
    $url = trailingslashit($base) . $endpoint;

    // prepare url param plus defaults
    $param = wp_parse_args($param, array(
        'access_key' => $apikey // do various filters or authenticate

    // prepare request args plus defaults
    $args = wp_parse_args($args, array());

    // build the full url
    $full_url = add_query_arg($param, $url);

    // first check for a cached version
    if ( $lifespan ) {
        $key    = $endpoint .'::'. md5($full_url);
        $cached = get_transient($key);

        if ( $cached !== false ) {
            return $cached;

    // make the request
    $request = wp_remote_get($full_url, $args);

    // parse the json response
    $response = json_decode( wp_remote_retrieve_body($request) );

    // check for request errors i.e. unauthorized, 503 error, etc
    if ( is_wp_error( $request ) || ( !in_array($request[ 'response' ][ 'code' ], array( 200, 201, 204 )) ) ) {
        return new WP_Error("request", 'unknown', '000');

    // check for api definied errors i.e. $response->success, $response->error, etc
    if ( empty($response) ) {
        return new WP_Error('type', 'message', 'code');

    // save a cached version
    if ( $lifespan ) {
        set_transient( $key, $response, HOUR_IN_SECONDS );

    return $response;

All in all, this is pretty light weight, and very quickly a custom table and caching via cron would be a better option than making a request on the fly and caching it after the fact. Hopefully the concepts here are helpful none the less!

Regular Expressions

Regular expressions… and I’m not talking about the ones you normally text with. It is an apt name however, due to it being something I use on a very “regular” basis.

My Initial Expression

When I first stumbled across regex, my initial expression was one of boredom. Let’s be honest, regex doesn’t exactly boast of the latest and greatest or the newest and coolest. Plus, it was officially first used in perl when I was like -13 years old… pretty sure CDs weren’t even a thing at that point. So who cares? Why not spend the time learning redux, or the newest task runner or bundler?

The Test of Time

Although it’s been around a long time, I would bet that it’s probably one of the most commonly used tools whether you know it or not. Just dig into any URL rewriting, the core of WordPress, or all of the find and replace tools out there. Behind the scenes regex has saved hours of work, and been implemented in one facet or another to all major development tasks or endeavors.

Alright, I get the history, so what does it do?

Regex, in a nutshell, is way to add logic to find-and-replace or pattern match — a “mapping” that allows you to be able to logically decipher a string into various pieces or patterns. What this does is, it allows your application to be able to quantify things like URLs, log messages, or anything else where you may want to extract specific pieces or patterns, but aren’t always sure what the contents of those strings might be.

For example, most web servers use pattern matching for their URL parsing. So when you see a URL: “” this gets matched by the webserver to tell it which web directory and post you want to view. WordPress will then extract the pieces from the URL using pattern matching to determine the post type, post name, page index of a blog feed, category, etc. Those extracted pieces get turned into variables like “” etc.

Going Beyond the Behind-the-Scenes

All that is cool to know, but it becomes a lot more applicable when you realize regex is usable in all the languages I’m aware of, as well as most find-and-replace tools including Atom, Google Spreadsheets, etc! It also becomes very handy when you need a customized permalink structure for a client and you want to make it fit in with WordPress’s pretty permalinks, or you have a massive file of log messages and want to extract specific parts in your text editor.

Here are some awesome tools and tips to learn more:

Developing WordPress Plugins

WordPress Plugins – For most people this is the bread and butter of their site. The theme provides the style, but except for the initial core features of WordPress, everything additional is done through plugins and extensions.

The Goal

The goal of this series of posts is to document my current practices as well as invite helpful suggestions and insights. I definitely am not a plugin expert, and this series of posts around WordPress plugins is just as much for my own benefit as anyone else’s, since I expect it to be a learning process. Continue reading “Developing WordPress Plugins”

Level Up Your Editor

Ahh, the text editor. One of the most prized developer possessions. And like any machine, you gotta look under the hood to see why no two are the same. We all have “our” theme, “our” packages, “our” snippets, etc.

One of the best ways I’ve improved my environment has been primarily by reading what other people appreciate and utilize in their workflow. I’d still like to improve my workflow, and have even been considering giving VS Code a test drive. So, keeping in line with my goal for the blog, here is my attempt to give back and share what I use.

Continue reading “Level Up Your Editor”

WP Engine: Post Launch Development

I recently ran into a situation when working with a site on WP Engine post going live. It was a bit of a struggle and I decided to come up with something better. I knew WP Engine had git push options, and had used them before, but that was only one of the pieces I needed for a more seamless workflow.

If you’re like me, you have a process for how you develop custom websites. It usually begins with your local development environment, version control of your code, and shared database for collaborative development etc…

However, that environment can tend to go quickly down the drain once a site goes live. You’re now at the mercy of the client-chosen hosting provider, never sure if your local or staging versions of the site are in true alignment with the live site, and every small edit from then on leaves a bad taste in your mouth on the site you put so much effort, organization, and passion into.

Continue reading “WP Engine: Post Launch Development”

The Struggle Was Real

The struggle bus

For a long time I’ve struggled to have any desire to be in a position where I attempt to put my opinions ‘out there’ without someone first asking for them. For a long time I told myself this was because people wouldn’t want to hear what I think. And although this might be true, I think something deeper has been the primary reason for this hesitation to speak out my ideas.

Continue reading “The Struggle Was Real”

Blogging Begins

Hello World… Isn’t that what every developer worth his salt is supposed to lead off with? Guess I can check that off my bucket list…

But more accurately, hello websphere! or whatever the cool kids are calling the interwebs these days. If you don’t know me, and couldn’t tell by my web address or logo, my name is PeterJohn Hunt, and it’s nice to meet you!

Who am I?

So what is this website you have stumbled upon? Well, this is my personal blog, which will be largely focused on development and problem solving of all kinds, although it will probably primarily be web-related. I plan to write my experiences, both past and present, goals, and general thoughts, mostly for my own benefit, to have it somewhere I can look back to, as well as possibly for the benefit of others to learn from what I have learned, am learning, and desire to learn.

Why start now?

Well, many reasons really. I’ve planned and thought about blogging for a long time, partially because of the many blog posts I’ve read and the impact they have made on me, and wanting to give back. Currently I work in a environment where open source is the primary backbone of a lot of the projects and work I do, and with that comes a pretty neat community of sharing and caring. I have benefited a lot from the open source philosophy and have long wanted to find a way to be not only a consumer, but a provider. I can honestly say as a self-taught web developer, that blog posts and others sharing their knowledge is literally the reason I am able to put food on the table for myself, my wife, and my son — and for that I am extremely grateful.

The inspiration

I’ve long planned to write a blog, and was constantly inspired to make that plan happen by people that I look up to, like Tom Mcfarlin and Pippin Williamson as well as twitter, Wordcamp posts, the open source community, WPTavern, and the many sites that have played an integral role in making me the developer I am today.

What took so long?

The first step is always the hardest, and sometimes it takes scraping off the fluff and jumping.

They say failing to plan is planning to fail… For me it wasn’t a case of failing to plan, but that I planned too much. For so long I’ve been held back by thinking that, as a self-proclaimed web developer, I wasn’t allowed to blog unless it was on a website I custom developed. Well, as the saying goes, “you’re your own worst client.” When building websites, I usually have the customer’s needs and goals to rely on when pushing forward and understanding the end goal. This is a lot harder when I’m working for myself and don’t have a technical goal, except for the elusive and general “start blogging”.

The push

How did I get out of that rut? I finally realized that my plan to blog was similar to my plans to learn new things like react, docker, and build a cross platform app: The first step is always the hardest, and sometimes it takes scraping off the fluff and jumping.

Sometimes you have to take a step back from where you are to truly see where you want to go.

So I decided to start at zero, and scrape away my preconceived ideas about what I needed to have in place before I could start blogging. I came to a point where I’ve been doing so much development, that I needed to pick up a different outlet, because frankly, I’m burnt out. I enjoy problem solving, creativity, learning, collaboration, coding. But too much of something good can quickly be overwhelming. I want to diversify my portfolio per se. I’ve found that attempting to workout has improved my problem solving and has made me a better developer. Similarly, I think writing and attempting to learn together with other people through blogging will do the same thing. Sometimes you have to take a step back from where you are to truly see where you want to go.

Moving forward

So here I am. My first blog post, a great theme by Array – a direct ripoff from Tom Mcfarlin (although I hear he is gonna update his site, which won’t make me look quite as much of a copycat), and a world of opportunity to learn new things. Check back soon for new posts!