最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Change default search URL slug in wordpress with Custop Post Type as Search target

programmeradmin0浏览0评论

I want to change default search page URL from:
/?s=background&post_type=download
to:
/

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?

I want to change default search page URL from:
http://example/?s=background&post_type=download
to:
http://example/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?

Share Improve this question edited Oct 13, 2020 at 1:56 Howdy_McGee 20.9k24 gold badges91 silver badges177 bronze badges asked Oct 10, 2020 at 11:09 Vijay ThakorVijay Thakor 211 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 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' ); 
发布评论

评论列表(0)

  1. 暂无评论