Function Friday #10: change content based on query strings

Function Friday #10

Every Friday, I’m sharing code snippets that I use to customize WordPress. Feedback/suggestions are always welcome! For more information, check out the first post in the series.


When I need a way to change content on a page based on how the visitor got there, I usually rely on query strings in the URL. If the URL looks like this: example.com/?bestdoctor=tennant

then I can do this in my PHP file (e.g. page.php):

<?php if ( isset( $_GET['bestdoctor'] ) && ! empty( $_GET['bestdoctor'] ) ) {
    if ( 'tennant' == $_GET['bestdoctor'] ) {
        echo 'Correct. Tennant is indeed the best Doctor.';
    } else {
        echo 'Error.';
    }
} ?>

The first if statement has two conditions:

  1. Check whether the “bestdoctor” variable is set at all, and
  2. Make sure the variable isn’t empty.

Once I know that the “bestdoctor” variable has a value of some kind, the second if statement checks whether that value is “tennant”. If it is, it displays one message. If the value is anything other than “tennant”, it displays a different message.

Note that this is not a secure way to hide content, i.e. putting protected content at example.com/?protected=true does not make it protected. Anyone with the URL (plus the query string) can access the content. It’s rather a way to display different data depending on how someone got to the page in question.

The code

For example, you might want to show different tax-inclusive prices to people depending on their location. On your Pricing page (perhaps using a custom page template?) you could add this code:

<?php
    // Get the value of the location variable
    $location = $_GET['location'];

    if ( isset( $location ) && ! empty( $location ) ) { // If the location variable is set, display correct prices
        // Store the tax rates in a variable
        if ( in_array( $location, array( 'alberta', 'northwest-territories', 'nunavut', 'yukon' ) ) ) {
            $tax = '0.05'; // 5%: Alberta, Northwest Territories, Nunavut, Yukon
        } elseif ( in_array( $location, array( 'new-brunswick', 'newfoundland-and-labrador', 'nova-scotia', 'prince-edward-island' ) ) ) {
            $tax = '0.15'; // 15%: New Brunswick, Newfoundland and Labrador, Nova Scotia, Prince Edward Island
        } elseif ( in_array( $location, array( 'manitoba', 'ontario' ) ) ) {
            $tax = '0.13'; // 13%: Manitoba, Ontario
        } elseif ( 'british-columbia' == $location ) {
            $tax = '0.12'; // 12%: British Columbia
        } elseif ( 'quebec' == $location ) {
            $tax = '0.14975'; // 14.975%: Quebec
        } elseif ( 'saskatchewan' == $location ) {
            $tax = '0.10'; // 10%: Saskatchewan
        } else {
            $tax = 0; // 0%: everywhere else
        }

        // Calculate the prices
        $large = 50 + ( 50 * $tax );
        $small = 25 + ( 25 * $tax );

        // Round up the results with two decimal places
        $large = number_format( $large, 2, '.', '' );
        $small = number_format( $small, 2, '.', '' );

        // Display the results
        echo 'Large box: $' . $large . '<br />
        Small box: $' . $small;
    } else { // Either no variable is set or it is empty, so ask for their location and reload the page
        echo 'Select your province/territory:<br />
        <a href="?location=alberta">Alberta</a><br />
        <a href="?location=british-columbia">British Columbia</a><br />
        <a href="?location=manitoba">Manitoba</a><br />
        <a href="?location=new-brunswick">New Brunswick</a><br />
        <a href="?location=northwest-territories">Northwest Territories</a><br />
        <a href="?location=newfoundland-and-labrador">Newfoundland and Labrador</a><br />
        <a href="?location=nova-scotia">Nova Scotia</a><br />
        <a href="?location=nunavut">Nunavut</a><br />
        <a href="?location=ontario">Ontario</a><br />
        <a href="?location=prince-edward-island">Prince Edward Island</a><br />
        <a href="?location=quebec">Quebec</a><br />
        <a href="?location=saskatchewan">Saskatchewan</a><br />
        <a href="?location=yukon">Yukon</a>';
    }
?>

I’ll break this down section by section.

Get the value of the location variable

$location = $_GET['location'];
if ( isset( $location ) && ! empty( $location ) ) {
    // do stuff
} else {
    // do other stuff
}

Start by storing the location string’s value in a variable so you can easily reference it throughout. Then set up an if statement that checks whether the variable is set/not empty, and display page content accordingly.

Store the tax rates in a variable

if ( in_array( $location, array( 'alberta', 'northwest-territories', 'nunavut', 'yukon' ) ) ) {
    $tax = '0.05'; // 5%: Alberta, Northwest Territories, Nunavut, Yukon
} elseif ( in_array( $location, array( 'new-brunswick', 'newfoundland-and-labrador', 'nova-scotia', 'prince-edward-island' ) ) ) {
    $tax = '0.15'; // 15%: New Brunswick, Newfoundland and Labrador, Nova Scotia, Prince Edward Island
} elseif ( in_array( $location, array( 'manitoba', 'ontario' ) ) ) {
    $tax = '0.13'; // 13%: Manitoba, Ontario
} elseif ( 'british-columbia' == $location ) {
    $tax = '0.12'; // 12%: British Columbia
} elseif ( 'quebec' == $location ) {
    $tax = '0.14975'; // 14.975%: Quebec
} elseif ( 'saskatchewan' == $location ) {
    $tax = '0.10'; // 10%: Saskatchewan
} else {
    $tax = 0; // 0%: everywhere else
}

This creates a variable called tax and sets its value based on the location.

The first condition in the if statement checks whether any items in the array (Alberta, Northwest Territories, Nunavut, or Yukon) are in the location variable – if they are, the correct tax percentage is 0.05 (5%).

For the tax rates that are only true for one province, the in_array function is unnecessary, so you can do a simple == (equal to) check instead.

Calculate the prices

large = 50 + ( 50 * $tax );
$small = 25 + ( 25 * $tax );

This adds the base price of our two imaginary products (“Large” and “Small”) to their correct tax amounts. Math!

Round up the results to two decimal places

$large = number_format( $large, 2, '.', '' );
$small = number_format( $small, 2, '.', '' );

The handy number_format function turns the calculated amounts into dollars and cents. If you end up with a number like 57.4875 (hi Quebec!), this will round it up to 57.49.

Display the results

echo 'Large box: $' . $large . '<br />
Small box: $' . $small;

Finally, display the total prices.

No query string? No problem!

echo 'Select your province/territory:<br />
<a href="?location=alberta">Alberta</a><br />
<a href="?location=british-columbia">British Columbia</a><br />
<a href="?location=manitoba">Manitoba</a><br />
<a href="?location=new-brunswick">New Brunswick</a><br />
<a href="?location=northwest-territories">Northwest Territories</a><br />
<a href="?location=newfoundland-and-labrador">Newfoundland and Labrador</a><br />
<a href="?location=nova-scotia">Nova Scotia</a><br />
<a href="?location=nunavut">Nunavut</a><br />
<a href="?location=ontario">Ontario</a><br />
<a href="?location=prince-edward-island">Prince Edward Island</a><br />
<a href="?location=quebec">Quebec</a><br />
<a href="?location=saskatchewan">Saskatchewan</a><br />
<a href="?location=yukon">Yukon</a>';

When the location variable is not set or is empty, instead of displaying the prices we’ll ask the visitor to select a location. Clicking one of these links reloads the same page, but with the appropriate query string appended to the URL.

In case you’re wondering… for the sake of brevity, this code assumes you’re charging each province/territory’s full sales tax rate (GST + PST). Usually you wouldn’t do that, but this is a code example, not a tax example!

Where does it go?

None of this code is actually WordPress-specific! But presumably you’re creating some custom functionality for a specific page with this code, so it should go in one of your theme files. More thoughts on where to put your code is in the first post in the Function Friday series.

Resources

Leave a Reply

Your email address will not be published. Required fields are marked *