我正试图根据GET参数重定向到特定的帖子。GET参数的值是特定自定义字段的值。
例如:
http://somedomain.com/wordpress/?fid=xyzzy
当一个帖子匹配时,我会让它工作。但是,如果没有匹配,它就不能正常工作。
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;
}
以及
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 );
}
}
我希望这会转到cnn。com与404错误,如果不匹配。但是,我得到了博客的主页,状态为200。
有什么想法吗?谢谢
最合适的回答,由SO网友:Bainternet 整理而成
删除foreach之后的else:
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;
}
}
$url = \'http://cnn.com/\';
wp_redirect( $url , 404 );
exit;
}else{
return $wp;
}
}