How to get a URL parameter from a URL with get_query_var?

I managed to find a solution with some help from some developers at the theme.co apex forum.

I needed to get two query strings from my URL www.randompage.com/tokensuccess/?token=token&username=username called token and username.

In order to get this I added the following code to the functions.php code:

function add_query_vars_filter( $vars ){
  $vars[] = "token";
  $vars[] = "username";
  return $vars;
}

add_filter( 'query_vars', 'add_query_vars_filter' );

get_query_var('token');
get_query_var('username');

This inserted the two query strings into the variables token and username

I then added the following code to the page.php file in order to print the values and insert them into the database.

<?php if (is_page('tokensuccess')) { if (get_query_var('token')) print "token = $token"; }  ?>

<?php if (is_page('tokensuccess')) { if (get_query_var('username')) print "username = $username"; }  ?>

<?php if (is_page('tokensuccess')) { 
    $token = get_query_var('token');
    $username = get_query_var('username');
    if( $token && $username ){

        global $wpdb;
        $wpdb->insert( 
            'wp_token',
            array( 
                'token' => $token, 
                'username' => $username 
            )
        );
    }
}

?>

So now I can send a link with query strings to my customer and automatically get his/her token and name.

Leave a Comment