如标题,我想更改当前网址:
example.com/?s=foo
致:
example.com/search?s=foo
如果未设置“s=”,则显示所有不带任何术语和过滤器的帖子。
请尝试这个:
wp_redirect(add_query_arg('s', $_GET['s'], home_url("search")));
而不是
wp_redirect(home_url("/search/").add_query_arg('s', $_GET['s']));
请查看 home_url 和 add_query_arg 的文档。
这段代码对我有用 - URL 结构是
/search/?s=term
并且还包括分页。
// This part adds rewrite rules to handle both the base search URL
// and the paginated search URLs.
function custom_search_rewrite_rule() {
add_rewrite_rule('^search/page/([0-9]+)/?$', 'index.php?s=&paged=$matches[1]', 'top');
add_rewrite_rule('^search/?$', 'index.php?s=', 'top');
}
add_action('init', 'custom_search_rewrite_rule');
// This part ensures that the redirection logic handles the pagination
// properly. It checks if the request is a search, is not in the admin
// area, and doesn't already use the /search/ structure. If the search
// has a page number (paged), it appends that to the URL.
function custom_search_redirect() {
if (is_search() && !is_admin() && strpos($_SERVER['REQUEST_URI'], "/search/") === false) {
$search_query = get_query_var('s');
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$url = home_url("/search/?s=") . urlencode($search_query);
if ($paged > 1) {
$url = home_url("/search/page/$paged/?s=") . urlencode($search_query);
}
wp_redirect($url);
exit();
}
}
add_action('template_redirect', 'custom_search_redirect');
添加代码后请记住刷新永久链接: WordPress > 设置 > 固定链接 > 单击[保存更改]