此解决方案无需创建新页面或更改任何内容。
我们将:
1。设置新的重写规则并添加新的查询变量
2。在“pre\\u get\\u posts”钩子中捕获该情况,获取我们需要的帖子并执行重定向
请注意,如果您有多篇具有相同keyword_meta
值,这可能无法按计划工作。我尚未对此进行检查,将选择第一个匹配的帖子。
代码应进入functions.php
或类似:
add_action( \'init\',
function () {
add_rewrite_rule(
\'^(go)\\/([^\\/]+)$\',
\'index.php?redirection=$matches[2]\',
\'top\'
);
add_filter( \'query_vars\',
function ( $vars ) {
$vars[] = "redirection";
return $vars;
}
);
}
);
add_action( \'pre_get_posts\',
function ( $query ) {
if ( $redirection = get_query_var( \'redirection\' ) ) {
// Change this:
$keyword_meta = \'keyword_meta_field_name\';
$redirection_url_meta = \'redirection_url_meta_field_name\';
$post_type = \'post\';
$args = [
\'meta_key\' => $keyword_meta,
\'meta_value\' => $redirection,
\'posts_per_page\' => 1,
\'post_type\' => $post_type,
];
$post_query = new WP_Query( $args );
$posts = $post_query->get_posts();
// If no posts found, redirect back to referer
if ( count( $posts ) < 1 ) {
wp_safe_redirect( wp_get_referer() );
}
$redirection_url = get_post_meta( $posts[0]->ID, $redirection_url_meta, true );
// If no redirection URL found, redirect back to referer
if ( ! $redirection_url ) {
wp_safe_redirect( wp_get_referer() );
}
// Finally, do the redirection
if ( headers_sent() ) {
echo( "<script>location.href=\'$redirection_url\'</script>" );
} else {
header( "Location: $redirection_url" );
}
exit;
}
return $query;
}
);
Please do not forget to refresh your Permalinks in the dashboard (open Settings > Permalinks and click on Save Changes).