我希望我的wordpress搜索可以在自定义搜索中的特定类别上工作,默认情况下,这实际上可以正常工作example.com/categoryname/?s=keyword
但我想让它像这样工作example.com/categoryname/search/keyword/
我有下面的代码,但它只适用于urlexample.com/search/keyword
function wp_change_search_url() {
if ( is_search() && ! empty( $_GET[\'s\'] ) ) {
wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( \'s\' ) ) );
exit();
}
}
add_action( \'template_redirect\', \'wp_change_search_url\' );
但如果我尝试
example.com/categoryname/search/keyword/
我收到404错误页
请我需要帮助,我希望它在类别内工作。
最合适的回答,由SO网友:Sally CJ 整理而成
您可以使用add_rewrite_rule()
:
add_action( \'init\', function(){
// Non-paged requests. E.g. example.com/categoryname/search/keyword/
add_rewrite_rule( \'^categoryname/search/([^/]+)/?$\',
\'index.php?category=categoryname&s=$matches[1]\',
\'top\' );
// For paged requests. E.g. example.com/categoryname/search/keyword/page/2/
add_rewrite_rule( \'^categoryname/search/([^/]+)/page/(\\d+)/?$\',
\'index.php?category=categoryname&s=$matches[1]&paged=$matches[2]\',
\'top\' );
} );
Be sure to flush the permalinks — simply visit the Permalink Settings page.