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

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

I have the below code but it only work on the url example.com/search/keyword

function wp_change_search_url() {
    if ( is_search() && ! empty( $_GET['s'] ) ) {
        wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) );
add_action( 'template_redirect', 'wp_change_search_url' );

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

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

1 Answer 1


You can use add_rewrite_rule():

add_action( 'init', function(){
    // Non-paged requests. E.g. example.com/categoryname/search/keyword/
    add_rewrite_rule( '^categoryname/search/([^/]+)/?$',
        'top' );

    // For paged requests. E.g. example.com/categoryname/search/keyword/page/2/
    add_rewrite_rule( '^categoryname/search/([^/]+)/page/(\d+)/?$',
        'top' );
} );

Be sure to flush the permalinks — simply visit the Permalink Settings page.

  • It works but is there anyway to replace the /search/ to anything else?
    – XATA
    Jul 11, 2019 at 8:27
  • Sure.. you can use a different slug (e.g. /find-posts/) or path (e.g. /search/posts/), just make sure to test it and confirm it doesn't conflict with existing permalinks/rules.
    – Sally CJ
    Jul 12, 2019 at 13:39
  • Thanks I have fixed it.
    – XATA
    Jul 15, 2019 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.