rewrites

TUTORIAL: Building Custom Rewrite Endpoints in WordPress

Recently I concluded a sizable project that involved deep integration with an external API. I was responsible for creating content pages based outside of WordPress. To be clear, the pages would use an internal WP template, but all the content was generated using this external API.

In order to make this work within the WordPress Rewrite system and serve pages that WordPress knew how to handle in a non-traditional way, I had to tackle this in a multi-prong way: using the template_redirect as well as the built in Rewrite API.

Note: I’m not giving away the full sauce here as the project is non-open source. As well, I’ll be abstracting some stuff a bit. If you’re smart, you can fill in all the blanks regarding how to fully implement this.

First we need a base class:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php

class Base_Class {

  public function __construct() {
    $this->hooks();
  }

  public function hooks() {
  }
}

new Base_Class;

This is the base of pretty much every class I write as part of a plugin in WordPress. If you don’t follow Object Oriented coding practices, start now.

The next step is to register some variables with WordPress. Because WordPress is using the template_redirect hook to get the proper template files, you will often lose necessary query string variables, and you definitely can’t use them in an endpoint (i.e. /foo/bar) without WordPress knowing about them.

So let’s register them using the query_vars filter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
class Base_Class {

  public function __construct() {
    $this->hooks();
  }

  public function hooks() {
    add_filter( 'query_vars', array( $this, 'query_vars' ) );
  }

  public function query_vars( $qv )
  {
    $qv[] = 'foo';
    $qv[] = 'bar';
    return $qv;
  }
}

new Base_Class;

After this, we want to actually create some rewrite endpoints. In this example, I want to allow permalinks like /foo/content-slug/ and /bar/content-slug. With the following code that adds a rewrites() method to the class, and hooks on the generate_rewrite_rules filter, we can create these two endpoints. In our imaginary template, we would use get_query_var() function to handle logic for display purposes, but that’s outside of this article scope.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
class Base_Class {

  public function __construct() {
    $this->hooks();
  }

  public function hooks() {
    add_filter( 'query_vars', array( $this, 'query_vars' ) );
    add_filter( 'generate_rewrite_rules', array( $this, 'rewrites' ) );
  }

  public function query_vars( $qv )
  {
    $qv[] = 'foo';
    $qv[] = 'bar';
    return $qv;
  }

  public function rewrites( $rules )
  {
    global $wp_rewrite;

    $new_rules = array(
        'foo/([a-z]+)/?$' => 'index.php?pagename=wppage-holder&foo=' . $wp_rewrite->preg_index(1),
        'bar/([a-z]+)/?$' => 'index.php?pagename=wppage-holder&bar=' . $wp_rewrite->preg_index(1),
    );
   
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    return $wp_rewrite->rules;
  }
}

new Base_Class;

Specifically, note the new rewrite rules and how they are structured. If those permalink structures identified above match these new rules, then we will pass the request on and use the template file designated for a page (that you do have to create in WordPress, by the way) with the slug ‘wppage-holder’. This can be done by designating a template file on the page edit screen or by naming the template as page-wppage-holder.php in your theme – again, outside the scope of this article.

If the permalink matches foo, we pass the foo variable on. If it matches bar, we pass the bar variable on. Logic on the other end left to you.

This is where I have to stop using this example, for client confidentiality purposes, but imagine what is possible now if you extend this and use the template_redirect hook to handle some custom redirects leveraging wp_redirect()?

Imagine. :)

Drawing by Romancement on Flickr. Used by Creative Commons.

Five Articles I Wish I could Take Back

Last night I was going through Google archives looking for a post (that I never found) from 2007-2008. I went through 30 some pages of search results and remembered some of the older content I wrote. Some of it is stuff I either wish I didn’t write or I don’t agree with anymore. So I figured I’d share some of these posts and explain why I feel differently today:

It’s a Read/Write/Execute Web and We Just Live in It.

In this post from 2009, I posit that the first generation of the web was a read-only web. It was website that were not engaged with outside of simply reading. The second generation of the web was a “read/write” web marked by social interaction. The third I called a “read/write/execute” web where I railed on the future of the internet being API oriented and that government should

Drawing by Romancement on Flickr. Used by Creative Commons.

get on board with open data initiatives at the time.

Where I have a modestly different view today and I did slightly alude to it back then, is that the next generation of the web would actually be mobile. That prediction would have been true, and while APIs have played a significant role in making that happen, the APIs were merely a means to an end.

There are hundreds of thousand apps on the Apple app store and Android Market, not to mention other available app stores out there. Games now are played largely on smartphones and tablets as the shift away from consoles, while mild, is undoubtable. Today, with HTML5 and CSS3, websites are being creative with “responsive” design that allows for appropriate displays on appropriate devices.

Fun Fact: In 2004, I mused about what a world look like if we were not dependent on keyboards and mouses. I think we see that world in front of us now.

Are People Talking About You?

Originally published in 2007, I rode a train of personal brand for a long time. Not in that I had it. Everyone has something and some people have more than others. It’s actually not personal brand. It’s just reputation. I have a reputation. I have a reputation as a no-BS guy that doesn’t have a lot of respect for drama professionally or personally. I’m a confidant and advisor and I know WordPress really well. I get clients via word of mouth because I have a reputation for great work that speaks for itself with a fairly in depth intimacy with the WordPress core code. That’s reputation, but if you must, you can call it personal brand.

Regardless, I wrote this in that article:

It’s important to create great “stuff” (define “stuff” for yourself). It’s really important to stand out above the crowd. It’s more important to get other people talking about you. You are a brand. You are a subject matter expert. Well, you have the potential to be a subject matter expert. But you’re not yet. Not if no one is talking about you when you’re not around.

Aaron, you had me until, “It’s more important to get other people talking about you.”

This is why I was completely wrong. Nobody knows Mike McDerment. Well a lot of people do, but he isn’t a household name in tech or startups. However, he is the CEO of the largest cloud accounting company in the world. He built Freshbooks from the ground up to solve a problem that he had in 2003 (I just read his back story today).

Similarly, do you know Jason Cohen? You might know him because I’ve mentioned him or because you use WP Engine but otherwise, Jason isn’t a flashy guy. When I got the call from Jason right before moving to Austin to come help start WP Engine, I was thinking he was another guy named Cohen. I had no idea how successful and amazing he was. He wasn’t worried about promoting himself. Product is everything and product speaks for itself.

So I entirely disagree with my 2007 theory of self-aggrandizement. The only reason you have to worry about personal brand is if you’ve got nothing going for you. Otherwise, shut up and do epic shit. The rest will follow.

Age of Exploration 500 Years Later

First of all, this story is all fluff. I tell a nice story of explorers and all but it takes me to the last paragraph to even make a point, much less a thesis statement. And even then, I’m unsure of my point.

Imperial Stout
Photo by Brostad. Used by Creative Commons

What I think I was trying to say is that technology and, more specifically, embracing technology and change makes us better business people, better communicators, better humans.

If I had to rewrite the end of this post, I’d say this:

All of these explorers that went before, discovered new lands, races, tribes, experiences and opportunity opened up the door to new innovations. They were able to lay the groundwork and stepping stones for new expansion of influence and find new technologies that would allow for growth into the Industrial age.

I would then use the example of the Imperial Stout created in England for the Queen of Russia:

Through the expansion of the Russian Empire, King Peter the Great of Russia discovered British Stouts. As they became popular among Russians, a problem emerged. There was no way to get these stouts in Russia because the trip was so long that the beer would spoil before arrival. In the 1800s, an English brewery, responding to demand, developed a way of “hopping” their stouts in such a way to allow the beer to be preserved and delivered to Queen Catherine of Russia. Thus, this more hoppy version of the typical stout became known as the Russian Imperial Stout, or just the Imperial Stout.

I would use that segue to explain that even in our technology-centric world, it takes innovators developing technology in order for other, new technologies to emerge. A classic example of this from the programming world is that of Ajax, an extension of JavaScript which has been around for years. Ajax is a technology that allows background communication with servers without the page reloading. Without Ajax being developed a few years ago, the interactivity we have come to expect on sites everywhere would not be able to exist.

So it’s not that I disagree with myself so much as I didn’t explore the real premise of the article enough.

Roadmap to Victory at the Washington Post

This article is still an interesting one. On one side, I saw the Washington Post, and traditionally print-based journalism, as a dying trade. On the other I made a naive assumption that newspapers exist for the sake of journalism.

Both of these premises are wrong. Let’s address both presuppositions.

Traditionally print-based journalism is alive and well, as it should be. It isn’t going anywhere, nor should it. Blogs and digital media are not in competition with newspapers. They complement newspapers. Both sides serve different roles. While it’s true that newspapers (print) can’t break news anymore, they should count their blessings.

There are no opportunities to destroy credibility with Dewey Beats Truman moments (or more recently, Mandate Struck Down, as famously misreported by CNN). There are plenty of opportunities for solid, in depth investigative reporting-style journalism. I know it costs money. So save money by not trying to break news and let the digital sources do that.

Secondly, my cynical take feeds right into that last sentence and is why the challenge lies in money. Journalism today is an art, and is a respectable skill, trade and profession. But news organizations aren’t run by journalists. They are run by business people. Many of them are not non-profits, so they are implicitly for-profit. That means the bottom-line, which is dictated by readership, circulation and sometimes the ratings of television sister networks, are what inform the decisions of the company.

Samuel Zell, owner of the Tribune Company, ran his media empire as an entertainment company and not a journalism company. Guess what? Tribune is still trying to emerge from bankruptcy protection.

Let’s get back to the Washington Post, though. When I wrote this story, WaPo was trailing in the digital race. Today, they did everything other than what I suggested in my piece and have become one of the foremost digital journalism centers around. Their blogs, including Capital Weather Gang and DC Sports Blog are stellar and I still read them regularly, even though neither pertain to me anymore.

Unlike when I wrote this post, WaPo’s digital and print operations are integrated, instead of separate. Online metrics are key and closely watched. Online traffic is the indicator of success at the Post. Circulation is not. Subscriptions are not. Traffic. Eyeballs on their apps, their blogs, their articles. That’s the important metric at the Post. No longer are digital operations a second class citizen. They are equal or greater than print.

Even the New York Times sees it:

They can look at where online visitors are when they read the site. And if their computers are registered with a government suffix — .gov, .mil, .senate or .house — editors know they are reaching the readers they want. “That’s our influential audience,” Mr. Narisetti said. “If a blog is over all not doing that great but has a higher percentage of those, we say don’t worry about it.”

The Washington Post is smarter than I am, clearly, and I applaud them for it.

Valleyboys: It’s All About the Money

Wow. How far off the mark can I be? This article, which matter-of-factly states something that was anything-but-fact, is a clear example o my lack of experience in 2007. In 2007, I apparently thought I knew everything there was about running a startup and raising funding. That from a perspective of someone who was  just over a year out of the corporate world working for my first startup. I wasn’t a founder nor had I raised money. I didn’t understand a thing about reputation (there’s that word again) of founders, the importance of co-founders, how to safely determine a valuation based on things like profit and loss, revenue, the value of burn, the value of users and more factors that go in to that process.

I don’t really know why I was so pissy at the Valley, but in 2012, let me go on record and say that it’s not all about money in the Valley and there are a lot of people working hard to create value. Many do raise money, but many bootstrap as well. There’s pros and cons to both, and that’s left to a different article.

In my defense, there is some absurd money flying around not just in the Valley, but everywhere. For instance, I still don’t see the reasoning behind a $30M raise on an 8x valuation for Path, a round that included Virgin empire mogul Sir Richard Branson. That company has pivoted so many times and still doesn’t seem to have a clue what it’s doing. Nor do I understand the $1 BILLION Instagram buyout by Facebook.

Here’s the money line (see what I did there?). Whether there’s a lot of money flowing or not is not the question. It is a question, but not the question. The question is whether there are good, innovative products being built that create value in the marketplace. If that can be done with no money, great. If it requires funding money on orders of magnitude, that’s a decision that the investors and entrepreneurs have to make. Money doesn’t come without strings. Big raises with low revenue and no profit generally mean the investors get more of the company and if the company sells, then the founders get less. But then big raises for profitable companies with low burn and high user numbers could also mean that the investors just want a piece of the action, even if they don’t get a big piece of the pie. But there’s always strings and the amount of money matters less than the percentage of ownership and the length of runway as it relates to a burn rate and overhead.

So if I believed in deleting articles entirely, this one would be a prime candidate. :)

In the spirit of making sure I’m not perceived as a douchebag, here are some good article I wrote many moons ago. Enjoy!

Friends vs. Fans, The Most Expensive Question, Social Media: How Much is Too Much?,

Turning the Resumé on its Face

Resumés suck. They suck bad. Somehow, you need to convince a prospective employer that you are, in fact, the right candidate for a job. Or you might be and they should take a second look at you and maybe give you the time of day to put up a phone interview.

You have to convince someone that you are entirely worth the time and effort without ever speaking to them. It’s all got to be conveyed on this little 1-2 page document that gives a snapshot of everything you are and can do professionally.

And you have to do it in a bad economy when people with Masters degrees are also looking for work. Maybe you too have a Master’s degree. That’s okay, you’re still competing against all the rest of them.

The traditional way of building a resumé is to provide a chronological context of every school and degree you’ve received along with every professional role over the last 7-10 years, give or take.

What do you do when you’re in the tech space and the requisite skills are constantly changing? What do you do when your role at the last 3 companies were essentially the same with little deviance in the job description?

Do as I do… flip your resumé on it’s face.

Let’s face it. If a company is going to hire you into a role, they want to know that you’re going to be innovative in your approach to the job and that you’re willing to think outside the box to do the best job you can. If they don’t, you probably don’t want to work for them anyway as they are plainly hiring you to just follow marching orders and that, let’s face it, sucks ass. There’s no place to achieve and rise to the top because you’re just doing things the way you’re told, by the book, all day every day. Sounds like a reason to drive off a cliff, if you ask me.

Let’s provide some context as to how this concept has worked for me for years.

In 1994, I graduated from a private high school in Annapolis, Md. I hated school but I went to a community college and decided not to do any general education coursework, as is typical. At the time, this school was piloting a program that shifted all the coursework from the police academy to the school with only firearms training being done at the academy. This was the county’s idea of slimming the budget. So I decided being a cop sounded like fun and I pursued a bunch of criminal justice work in my first year of college.

I dropped out after a year and pursued other interests.

Years later, I was given the opportunity with little experience to work in a federal data center for a government contracting company. I spent three years in that windowless data center watching my life slip away from me. It gave me a shot though.

As I started looking to move up inside the company, I realized that to do so meant punching some certification cards. I put a few small ones under my belt – enough to get a promotion to work desktop IT support as a contractor for the U.S. Navy. I did well in that role, consistently rating among the highest, knowledgeable techs on that contract.

When that contract expired and I was RIFfed (Reduction in Force), the company scooped me up into a similar role on the corporate side. Again, I was able to perform at a high level and by the time I left in 2006, I was single-handedly responsible for the IT support of 7 offices around the Baltimore/Washington area.

I still had no formal education, so during this time, I went back to another community college and worked toward getting coursework under my belt that would allow me a 4-year degree at some point in the future.

That was until I said, “Fuck it”, and went into the startup world. For the past 6 years, I have worked at or started 3 startups and ran my own consulting business in between (as I still do today). I did some advisory consulting with the Air Force, wrote a book, and even taught some classes at the post-graduate level at major universities including American University. Not bad for no degree.

Today, I still have no formal education. I’m a few credit away from a 2-year degree which wouldn’t be worth the paper it was printed on. When I went back to school, my experience was such that I was teaching the teachers.

I can go into a diatribe about how higher education is broke in this country, but I feel like I would be preaching to the choir. While some of my experience can be translated as college credit, most is ignored despite the fact that, in my field, I am 5-7 years ahead of what they are teaching in colleges today. And while a 4 year degree would be fairly useless to me as the industry is ahead of academia, a Master’s could be quite handy. Sadly I can’t get a Master’s without a 4-year, but I digress.

Coming back to the point about the resumé. I have tremendous chronological gaps if I were to formulate my resumé in traditional fashion. Am I ashamed of having no degree? No. Do I want to highlight that fact? Hell no. It’s unfortunate that America’s HR departments have been trained by buffoons who play to the checkboxes instead of actual skill, but those are the rules we play by.

Instead, I present to you an achievement/skills-based resumé. Instead of discussing formal education or companies that have been worked at ad nauseum, try laying it out to highlight the things you’ve accomplished along the way. I begin my resume with several one-sentence paragraphs that describe achievements I’ve made professionally – not for a company, for me.

I then mention companies I’ve worked at, purely for the sake of context. I also use LinkedIn recommendations I’ve received over the years to highlight what others say about me.

These three steps provide the context needed for employers to decide if they want to talk to me. If I can humblebrag, I usually get phone interviews for the companies I want to talk to and they usually go deep into multiple rounds. I’m still working for myself because timing, pay or perks are off in the end, but I rarely fail to get the attention of someone who I want to work for.

Try this concept. Maybe A/B test between a resumé of the format I’m describing and a more traditional one and see which one gets more traction. It can’t hurt, right?

Oh and here’s my resumé.