如何使用同时使用字母和数字的查询变量在 Wordpress 中重写 URL?

How can I rewrite a URL in Wordpress with a query variable that uses both letters and numbers?

我想在 Wordpress 中使用页面和 URL 参数编写自定义重定向。基本上,我希望 /property/ABC123index.php?pagename=property&my_id=ABC123。这就是我所拥有的,但我认为我的正则表达式已关闭。

public function custom_rewrite_tag() {
    add_rewrite_tag('%my_id%', '([^&]+)');
}

public function custom_rewrite_rule() {
    add_rewrite_rule('^property/([^/]*)/?', 'index.php?pagename=property&my_id=$matches[1]', 'top');
}

add_action('init', [$this, 'custom_rewrite_tag'], 10, 0);
add_action('init', [$this, 'custom_rewrite_rule'], 10, 0);

我已经刷新了我的固定链接,但这不起作用。我也尝试删除下划线 (myid),但这也不起作用。我做错了什么?

来自 add_rewrite_tag 文档:

Retrieving the Value of a Rewritten URL

With a rewrite tag defined, you can now retrieve the value of your rewritten querystring variables using WordPress's $wp_query variable. To get the value of the above tag out of a rewrite, you could use the following in your page template:

$wp_query->query_vars['film_title']

Note that using $_GET on a rewritten URL will not work, even if the rewrite includes the querystring variables. You must use $wp_query.

考虑到这一点,您应该能够像这样访问模板中的变量:

...
global $wp_query;
var_dump($wp_query->query_vars['my_id']);
...

如果您仍然遇到问题,请尝试将您的正则表达式修改得更具体一些。在这种情况下,我们只接受字母数字字符 :

public function custom_rewrite_tag() {
    add_rewrite_tag('%my_id%', '([a-zA-Z0-9]+)');
}

public function custom_rewrite_rule() {
    add_rewrite_rule('^property/([a-zA-Z0-9]+)/?', 'index.php?pagename=property&my_id=$matches[1]', 'top');
}

add_action('init', [$this, 'custom_rewrite_tag'], 10, 0);
add_action('init', [$this, 'custom_rewrite_rule'], 10, 0);

如果有帮助请告诉我。