1

I want to change default search page URL from:
http://example.com/?s=background&post_type=download
to:
http://example.com/photos/background/

I tried to change the below function for the default search page:

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' );

The above function works ok but not working with custom post type searches.

In my theme I want to search only my custom post type named download and currently the function searches all posts & pages. What can I do?

1

Hi Vijay you can try to add post_type as query perameter in you redirect url check following changes in your code.

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

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.