I'm trying to redirect to a specific post based on a GET parameter. The value of the GET parameter is the value of a specific custom field.
For example:
http://somedomain.com/wordpress/?fid=xyzzy
I have this working when a post matches. But, it's not working properly when there is no match.
add_filter('query_vars', 'fid_query_vars');
function fid_query_vars($vars) {
// add fid to the valid list of variables
$new_vars = array('fid');
$vars = $new_vars + $vars;
return $vars;
}
and
add_action('parse_request', 'fid_parse_request');
function fid_parse_request($wp) {
// only process requests with "fid"
if (array_key_exists('fid', $wp->query_vars) && $wp->query_vars['fid'] != '') {
$args = array('post_type' => 'faculty_profile', 'meta_key' => 'wid', 'meta_value' => $wp->query_vars['fid'] , 'numberposts' => 1);
$redirect_to_post = get_posts($args);
if (!empty($redirect_to_post ) ) {
foreach ($redirect_to_post as $p) {
$link = get_permalink($p->ID);
wp_redirect( $link , 301 );
exit;
}
}
else {
$url = 'http://cnn.com/';
wp_redirect( $url , 404 );
}
}
I'd expect this to redirect to cnn.com with a 404 error, if there is no match. But, instead, I get the blog's homepage, with a status of 200.
Any ideas? thanks.