A question of communication
Your averagely sociable Musketeer in the 17th Century had it trickier when it came to the delicate subject of communicating with a paramour. Forget surreptitious emails, crafty text messages or the array of self-destructing messaging apps that the kids are all using these days.
No. These martial gentlemen of yesteryear were forced to pass messages by use of a third party… an indentured underling for example – one of their ‘lackeys’ as they were wont to call them.
Well, in the world of HTTP, things haven’t progressed much…
Modern day carrier pigeons
Hyper Text Transfer Protocol (HTTP) is the lingua franca of the web. It’s the technology used to deliver webpages from the server to your browser. It’s why web addresses start with the abbreviation http://
.
HTTP was, and has remained, a stateless protocol. That is to say one request to a webpage has no knowledge of the previous requests that might have occurred. This means a web page has no means of recognising choices you might have made on a previous page, or even on the same page viewed on a previous request.
Over the years, clever web developers have devised ways to overcome these limitations and send signals from one page to another, so knowledge of choices you make on one page can be communicated to the next. Much like those lackeys we spoke about earlier, or perhaps a modern day version of a carrier pigeon…
Hiding in plain sight
One of the oldest means of passing information from page to page is to hide it in the URL used to access successive pages. These URL parameters use the following syntax:
http://www.example.com/page.php?key=value
The question mark indicates the end of the web address of the page being served. This is followed by a key / value pair.
If you need more than one key / value pair, just separate them with ampersands.
http://www.example.com/page.php?key1=value&key2=value&key3=value
Adding the URL parameters to a page request is a breeze, simply encode them in a link:
The target page (page.php in this case) will then have access to the key / value pairs as if we had assigned the values to variables.
For extra credit, the URL parameters become superglobal variables in PHP and are accessible as such: $_GET['key']
To output them you should first check they exist (the page could be requested with or without the URL parameters appended):
However, there’s no need to concern yourself with this for the purposes of today’s topic as we’ll be using Ninja Forms to handle the URL parameters.
Good form
So what can you do with the information stored in these key / value pair URL parameters? Here are some common use-cases:
- Display confirmation of a choice made on the previous page
- Pass a unique reference that identifies the referrer (for example, your email campaign links should identify which campaign generated the click-through)
- Display unique content to certain visitors depending on where they were referred from
- Identify that a visit has been generated by an affiliate
- etc.
For the purposes of today’s example we’re going to dynamically pre-populate Ninja Forms fields based on which link the user clicks on the preceding page.
We’re going to pretend we’re selling fencing lessons in multiple tiers. The visitor will click a link in one of the tiers to be taken to a form for joining their chosen tier.
Let’s get started.
The code
First, we need a page describing our tiers. Let’s call it fencing-lessons.php
. Here’s the HTML from the relevant part of that page:
It’s also good practice to let WordPress know you intend to use custom URL parameters (so it doesn’t think the URL is being manipulated by a nefarious third party). It’s simple to declare your URL parameters in your functions.php file like so:
Ninja Forms
Next, we need the form to populate. The Ninja Forms core plugin is available fore free on the WordPress repo. This is all you need to complete this tutorial, but I recommend heading over to the Ninja Forms site to check out their paid addons. I especially like Front End Editor, File Uploads, Save User Progress and Multi Part Forms.
Install the plugin in the usual way (Plugins >> Add New
and search for it in the repo, or download the plugin .zip file and upload it to your server).
Still in the WordPress dashboard select Forms >> Add New
and add some fields as in the following screenshot:
Play with the settings in the other fields, but make sure the “Tier” field looks like this:
The key things to note here are:
- The field label is “Tier”. We’ll use this to identify the right field to manipulate in our code.
- We’ve ticked “Show list item values” so we can edit the visible label name and the value separately. “Value” is the unique name used to identify the field’s options in our code.
- The terms used in the value boxes must correspond with the terms you’re passing in the relevant URL parameter.
The secret sauce
And here’s the final part of the recipe… a piece of code that intercepts the form at creation time and checks for a “Tiers” field. If it finds one, it checks to see if the field has an option that corresponds with a tier value passed in a URL parameter. If it does, it makes this the selected option. Throw this bit of secret sauce in your functions.php:
And the important takeaways here are:
- The
ninja_forms_field
filter is called before any Ninja Forms form is rendered. It helpfully passes the form fields and their data into our function as an array, which we instantiate as$data
. - We check if the form has a field with a label of “Tier” and if there is a “tier” URL parameter. We can use the WordPress helper function
get_query_var('tier')
because we declared our custom URL parameters previously. - We iterate over the options available in the Ninja Forms list field with label “Tier” and check to see if one of them has a value that matches the passed URL parameter. If it does, we make it selected.
Mission accomplished. Mostly
And there you have it. We’ve successfully populated a Ninja Forms field with data passed via a URL parameter. Hopefully we’ve also learnt some neat new features of WordPress along the way.
The keen-eyed and inquisitive amongst you might have one question remaining though… the example shows how to pre-populate a Ninja Forms list field, but what about other field types, like text inputs? Fear not my apprentice, for that is even easier!
UPDATE
Thanks to Kyle B. Johnson (@kbjohnson90) a WP Ninja who works on the Ninja Forms plugin. He dropped by the comments to let me know that Ninja Forms core can now automatically detect URL parameters (also known as query strings) for text input fields. In the Advanced Settings section of the field, choose “Querystring Variable ->” from the “Default Value” dropdown and enter the key name from the URL parameter key / value pair that you want to use to populate that field. You’ll still need the above code for other field types.
Thanks again to Kyle for the following screenshot:
If you have any other questions, ask away in the comments or tap me up on Twitter or Google+.
à bientôt!