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: “https://peterjohnhunt.com/blogging-begins/” 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 “https://peterjohnhunt.com/index.php?post=blogging-begins” 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”