Pulling a parameter out of the URL of a WP link without “?” or being sent to a different page

Supposing you have a page created with the slug “referral”, you can add another segment to the page URL containing the employee ref number like this:

1- Register a new query variable e.g “employee_ref”

add_filter('query_vars', function ($query_vars){
    $query_vars[] = 'employee_ref';
    return $query_vars;
});

2- Using add_rewrite_rule function, add a new rule for the ’employee_ref’ to be equal to the last numeric segment of the page URL:

add_action('init', function (){
    add_rewrite_rule(
        '^referral/([0-9]+)/?$',
        'index.php?pagename=referral&employee_ref=$matches[1]',
        'top'
    );
});

3- Go to permalinks setting page on your WordPress dashboard and hit the “Save Changes” button to flush the rewrite rules–a mandatory step–.

4- The referral link now will look like “https://yourdomain.com/referral/345/”, where “345” is the employee ref number and you can catch it in PHP using:

get_query_var('employee_ref');

The code used in the first two steps can be placed inside your theme’s functions.php or a plugin file.

Leave a Comment