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

I have a specific requirement that my referral link be as simple as possible to type in manually (customer base is very low skilled) while simultaneously referring to an employee number who was responsible for the referral.

So, the referral links need to look like:

www.domain.com/referral/1555

Where 1555 is the employee ref number who sent this referral link, and it's the employee ref number that I'll be taking out of the URL. I'm using PHP snippets to deal with loading that data and handling it, but I need to land on the referral page inorder for that php snippet to fire.

How do I dictate to WP that any URL slug starting with referral, regarldes of what comes after, goes to my referral page and keeps the URL intact? The best I can do right now is land on the referral page but the URL gets reset to merely

www.domain.com/referral

Topic urls Wordpress parameter

Category Web


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.


You just need the Redirection Plugin and a little regex. There are good options on how to match the URLs in the plugin settings.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.