functions - How to rewrite wordpress search to work on specific category

I want my wordpress search to work on specific category within custom search, by default this actually work fine example

I want my wordpress search to work on specific category within custom search, by default this actually work fine example/categoryname/?s=keyword

but I want to make it work like this example/categoryname/search/keyword/

I have the below code but it only work on the url example/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' );

but if i try example/categoryname/search/keyword/ i get 404 error page

Please I need help I want it to work within the category.

I want my wordpress search to work on specific category within custom search, by default this actually work fine example/categoryname/?s=keyword

but I want to make it work like this example/categoryname/search/keyword/

I have the below code but it only work on the url example/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' );

but if i try example/categoryname/search/keyword/ i get 404 error page

Please I need help I want it to work within the category.

Share Improve this question asked Jul 10, 2019 at 19:07 XATAXATA 6712 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

You can use add_rewrite_rule():

add_action( 'init', function(){
    // Non-paged requests. E.g. example/categoryname/search/keyword/
    add_rewrite_rule( '^categoryname/search/([^/]+)/?$',
        'index.php?category=categoryname&s=$matches[1]',
        'top' );

    // For paged requests. E.g. example/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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745330929a4622872.html

相关推荐

  • functions - How to rewrite wordpress search to work on specific category

    I want my wordpress search to work on specific category within custom search, by default this actually work fine example

    3小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信