Skip to content

WordPress, REST, and RegEx

Dear Reader,

I’m going to add this to “Using the WordPress REST API“, but I thought I would blog it here as well.

I have a tendency to over think things.

Today, I was working on a REST API endpoint for a client and it needed to have RegEx in it. I hate RegEx with a passion usually reserved for XML, but unlike XML, it’s a necessary evil, so I dove into it.

1
/item/(?P<itemId>\d+)

That’s an example.

For the uninitiated, when you are defining a custom WordPress REST endpoint, one of the things you can do is put in Regex into the route definition and WordPress will use that to pull out content and make it a parameter. The code above defines an endpoint for

https://example.com/wp-json/my-namespace/v1/item/4

When run, it will make a parameter named itemId whose value is the 4 from the URI. It’s incredibly handy. They are very easy to work with, especially if you are using numbers like 4, or even 294875.  Strings…well, strings get tricky.

The above example expect a number (so no alpha, just numeric) and numbers are contiguous.  You don’t have numbers with a space in them. Phrases however, have spaces. And what I needed to pull out was a phrase. So, I did what I always do, I pulled out Regex 101, and started figuring this out. This is where the overthinking part comes in.

I got it working in short order, then I started thinking. “What if…”

  • What if There’s a query string at the end
  • What if there’s more to the URI
  • What if there’s a slash at the end
  • …what if

This is where I got into trouble. I lost a good 2-3 hours designing a beautiful piece of RegEx that handled every situation I could think of. It was art, if I do say so myself. The only problem was that once I pasted it into my WordPress REST Controller, it did not work.

So I did what every developer does, I assumed the problem had to be in WordPress. I rolled up my sleeves and found out how WordPress matches routes.

What WordPress does

WordPress matches REST routes in WP_REST_Server::dispatch() (wp-includes/rest-api/class-wp-rest-server.php)

1
$match = preg_match( '@^' . $route . '$@i', $path, $matches );
$path is the URI. IN my case
https://example.com/wp-json/my-namespace/v1/item/this%20item%20name
$route was the route I defined in regex.
1
item/(?P<itemName>[w+].*)[?|/|\$]
(I’m working from memory but I think that was it.)
If – and only if – I could set some pattern modifiers I could make it work…but I couldn’t.
Then I began doing the other thing that PHP developers do a lot, I began throwing var_dump();die(); into WP_REST_Server. I thought I needed to see what was going on. Turns out, the answer was there in front of me all the time.
I was assuming that WordPress was applying my RegEx standalone from everything else. If you look at the line above though, you can see that is uses the route that I define in it’s entirety.
  • It puts a ‘@’ at the beginning of it. This tells PHP that ‘@’ is the regex delimiter, not ‘/’ like usual
  • It adds the caret ‘^’ to match the beginning of the line
  • It concatenates the route I defined
  • It adds the $ to match the end of the line
  • It puts the ‘@’ to signify that this is the end of the RegEx
  • It adds the ‘i’ pattern modifier (the things I needed to tinker with) to indicate that all matches should be case insensitive
WordPress doesn’t worry about the query string, or anything after that because it’s already stripped it off. I don’t have to overthink this thing with subgroups and special characters, WordPress has got my back.
My finished product ended up looking like this:
1
item/(?P<itemName>w+.*)
This gives me a parameter named itemNamethat includes everything past item/ to the end of the line.

Conclusion

Stop over-thinking things. Sometimes just let the framework do it’s job. :)

Did I meantion I hate Regex? :)

Until next time,
I <3 |<
=C=

p.s. the section in the book will be more coherant. I’ve spent the day with RegEx so I’m a bit scatterbrained now. :)

Why I teach

Dear reader,

I am a selfish person. I do not generally like to share my time with anyone and would rather spend it doing the things I love like video games and scuba diving. However, I owe a debt that I am honor bound to repay.

I am where I am in life because others helped me get here. Yes, I am a self-taught programmer, I mean that in the traditional way of I have no formal training in software development. But self-taught does not mean that I did it all myself. I learned from others. I read their blogs, I listened to their podcasts, I went to their conference sessions. I did the learning, but others all around me taught, mentored, and generally lifted me up to where I am.

Knowing this, I spend a portion of every day trying to help others. Some efforts are more successful than others, but as long as I am trying, I am paying back the debt I owe.

Others sacrificed so I can be where I am. It is my duty to sacrifice so that I can lift the next generation of developers up higher than I could go. To lift them up on my shoulders so that they can stand there and see further than I ever could.

Until next time,
I <3 |<
=C=

Great writers read…a lot

Dear Reader,

Have you ever watched one of those movies where  a software developer (usually called a hacker) is sitting in front of 2 screens and on both of them code is scrolling by at a fast pace while the hacker nods knowingly like they are reading and understanding what they are seeing?

Yeah, that doesn’t happen.

A more common scenario is that a software developer will fork a repo, clone it locally, open their editor of choice and start reading through the code. Scrolling through it slowly. opening another edito for the same code and scrolling back up to a previous section and comparing the two. This goes on for a long time.

Reading other people’s code is probably the best way to learn how to program. If you know what the code does then reading the code shows you how someone else solved the problem.

Just like a great writer reads more than they write, a great software developer will read code, theirs and other peoples, more than they will write code. As a junior developer this goes double for you. Since you do not have a body of work to copy and paste from, you need to see how other people solved common problems so you can understand how to solve them yourself.

Until next time,
I <3 |<

You will fail

Dear Reader,

It has come out recently that while packing up to leave the White House, the previous administration’s  staffers left notes all over the place for incoming administration’s staffers stating “You will fail.” I am sure they meant this to be a subversive and demoralizing message meant to make sure that things did not get off to a good start. I’m not here to discuss what kind of people it takes to willfully wish other people fail and hope for the worst. I also have no idea if the messages were effective or not, that’s not the point here. 

The point I want to make about these notes is that they were absolutely right and on-point. Every person who received one of those messages did fail at some point, probably on that very day. Here’s the fun part, so did the people who wrote them. We are human, we all fail, it’s a fact of life. 

You will fail at some point today.

I will fail at some point today, for every value of today.

Whether it is missing a deadline, or not doing something you promised a friend you would do; at some point today, you will fail. I’m here to tell you that it’s ok, failing is how we learn.

In tech, some companies adopt the mantra of “fail fast” for that very reason. The faster we fail, the faster we can learn from that failure, and the faster we can learn what works.

It’s ok to try something new.

It’s ok to fail when you do.

It’s ok to get up and try again. 

You will fail. Own it. 

Until next time,
I <3 |<
=C=

I wanna be like my Roomba

Dear Reader,

I wanna be like my Roomba.

My Roomba kicks off every morning at 8:00 Am ET sharp and sets out to accomplish the day’s mission.

My Roomba does not feel like a failure if does not complete it’s given task in the allotted time.

My Roomba does not take into consideration that it failed yesterday before starting today.

My Roomba does not doubt itself and wonder if it is really qualified to clean the floor.

My Roomba faces each day knowing that it will do it’s job to the best of it’s ability and that’s good enough.

I wanna be like my Roomba.

Until next time,

I <3 |<