The way I do it. Note there may be a more straightforward way.
Step 1
Add a custom query_var
like this to record the redirect from/to variables
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' );
Step 2
Add foreach
loop that does something like this. This will add the rewrite rules to change http://example.com/foo
to 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]$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');
Step 3
Hook into the parse_request
filter to parse your request and redirect as necessary.
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');