WordPress自定义重写规则

I have a page in my wordpress site that pulls in data from a third party api. The data depends on a url parameter. If my url is example.com/profile/user1 than I need to pull data from the api from the user with the user account "user1".

I am having trouble getting wordpress to recognize the last url parameter. Right now, I am getting page not found. Here is my page code:

<?php
/*
Template Name: Profiles
*/

$gamertagurl = $_SERVER["REQUEST_URI"];
$gamertag = substr($gamertagurl, 9, -1);
$url = 'https://xboxapi.com/v2/'.$gamertag.'/profile';
$headers = array('X-AUTH: 718a17918628b41f8be806dfd5b27a20e8973d3f');

$session = curl_init($url); 
curl_setopt($session, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($session);

curl_close($session);

$myArray = json_decode($response);

$i = 0;
foreach ($myArray as $key => $value) {
    echo '<a href=' . $value->screenshotUris[0]->uri .'><img src=' . $value->thumbnails[1]->uri  . '/></a>';
    $i++;
    if($i==10) break;
}

echo '<pre>';
var_dump($myArray);
echo '</pre>';
?>

In my functions.php file, I have added:

function custom_rewrite_tag() {
    add_rewrite_tag('%gamertag%', '([^&]+)');
}
add_action('init', 'custom_rewrite_tag', 10, 0);

function custom_rewrite_rule() {
add_rewrite_rule('^profile/([^/]*)/([^/]*)/?','index.php?page_id=2&gamertag=$matches[1]','top');
}
add_action('init', 'custom_rewrite_rule', 10, 0);

Obviously, I have a mistake somewhere but I don't know where.

I figured out the problem.

I needed to remove the code in my functions file and add:

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

add_filter( 'query_vars', 'add_query_vars_filter' );

add_rewrite_rule('profile/([/])/([/])/?','index.php?page_id=2&gamertag=$matches[1]');