How to pass username in affiliate link in wordpress website

I need to pass current logged in user in wordpress website as SUBID in the affiliate link as follows.

Affiliate link format is like below.

https://affiliatenetwork.com/track?id=myuseridurl=https://nike.comsubid={subid}

I want to pass current logged in user as a subid in above link. I have written below code in functions.php.

if ( is_user_logged_in() )
{
    $userName = get_current_user_id();
}
----Need code here to pass $userName as subid ( mentioned in above link).------

Please help.

Topic url-rewriting php Wordpress parameter

Category Web


This code adds the subid parameter if does not exist to the current URL. Use this plugin to insert the php code: https://wordpress.org/plugins/my-custom-functions/

But you need to use add_action() to call this function somewhere.

function my_change_url() {
    global $wp;
    $current_url = home_url(add_query_arg(array($_GET), $wp->request));
    if ( empty($_GET['subid']) ) {
        $cuser = wp_get_current_user();
        $username = $cuser->user_login;
        $current_url = add_query_arg(array($_GET), $wp->request);
        $current_url = add_query_arg('subid', $username);
        $current_url = home_url($current_url);
    }
    return($current_url);
}

OR You may use a shortcode:

add_shortcode('affiliate_subid', 'my_change_url');

Put the short code anywhere on a page:

[affiliate_subid]

About

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