首页 > 解决方案 > 使用 add_rewrite_tag() 在 wordpress 中传递变量

问题描述

我已经搜索了很多使用 add_rewrite_rule() 和 add_rewrite_tag() 的完美方法

在阅读了 wordpress 文档后,我已经达到了这一点

在我的 function.php 中:

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

function custom_rewrite_rule() {
    add_rewrite_rule('^testpage/([^/]*)/?$','index.php?page_id=9&variable1=$matches[1]','top');
    add_rewrite_rule('^testpage/([^/]*)/([^/]*)/?$','index.php?page_id=9&variable1=$matches[1]&variable2=$matches[2]','top');
    add_rewrite_rule('^testpage/([^/]*)/([^/]*)/([^/]*)/?$','index.php?page_id=9&variable1=$matches[1]&variable2=$matches[2]&variable3=$matches[3]','top');
}
add_action('init', 'custom_rewrite_rule', 10, 0);

现在,我正在尝试获取变量 1,2 和 3 的值以在我的 testpage.php 中使用它

我用这个:

global $wp_query;
echo $wp_query->query_vars['variable1'];
echo $wp_query->query_vars['variable2'];
echo $wp_query->query_vars['variable3'];

问题 :

我能得到的唯一变量是变量 1 吗?

我既不能得到 variable2 也不能得到 variable3

注意:使用 $_GET[] 或 $_POST[] 不起作用

标签: phpwordpress

解决方案


推荐阅读