我做这件事的方式。注意,可能有一种更直接的方法。
步骤1添加自定义query_var
这样可以记录从/到变量的重定向
function my_custom_query_vars($vars){
//this allows you to store custom variables with rediect_from and rediect_to in the url
$vars[] = \'redirect_from\';
$vars[] = \'redirect_to\';
return $vars;
}
add_filter( \'query_vars\', \'my_custom_query_vars\' );
步骤2添加
foreach
这样做的循环。这将添加要更改的重写规则
http://example.com/foo
到
http://example.com/?redirect_from=foo&redirect_to=bar
function my_custom_rewrite_rules($wp_rewrite){
$new_rules = array();
$json = \'\';//get your json data and store it as this string
$json_array = json_decode($json, true);
foreach($json_array as $key => $value){
$new_rules[\'^\'.$key.\'$\'] = \'index.php/?redirect_from=\'.$key.\'&redirect_to=\'.$value;
}
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action(\'generate_rewrite_rules\', \'my_custom_rewrite_rules\');
步骤3钩住
parse_request
筛选以解析您的请求,并根据需要重定向。
function my_custom_parse_request($wp){
//we make sure the keys are present and not empty before we redirect
if ((array_key_exists(\'redirect_from\', $wp->query_vars)
&& !empty($wp->query_vars[\'redirect_from\']))
&& (array_key_exists(\'redirect_to\', $wp->query_vars)
&& !empty($wp->query_vars[\'redirect_to\']))){
wp_redirect(home_url(\'/\'.$wp->query_vars[\'redirect_to\']));
exit;
}
add_action(\'parse_request\', \'my_custom_parse_request\');