Skip to content

Instantly share code, notes, and snippets.

@nurbek-ab
Last active April 5, 2021 10:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nurbek-ab/d755ac3594c4ea9dd6c6 to your computer and use it in GitHub Desktop.
Save nurbek-ab/d755ac3594c4ea9dd6c6 to your computer and use it in GitHub Desktop.
Change wordpress search results permalink (base url, search base).
<?php
function nice_search_redirect() {
global $wp_rewrite;
if ( !isset( $wp_rewrite ) || !is_object( $wp_rewrite ) || !$wp_rewrite->using_permalinks() )
return;
$search_base = $wp_rewrite->search_base;
if ( is_search() && !is_admin() && strpos( $_SERVER['REQUEST_URI'], "/{$search_base}/" ) === false ) {
wp_redirect( home_url( "/{$search_base}/" . urlencode( get_query_var( 's' ) ) ) );
exit();
}
}
add_action( 'template_redirect', 'nice_search_redirect' );
?>
@vinigarcia87
Copy link

Bug: Gets 404 when you pass no parameters for the search

@adebo4all
Copy link

This works perfectly for me on my site: https://nnn.com.ng/. Other solution throw a 404 error for me.

/**
* initiate a change of the wordpress default search page slug to the new search page slug.
*/
add_action( 'init', 'dsfs' );

function dsfs()
{
    $GLOBALS['wp_rewrite']->search_base = '%your_search_string%';
}

/**
* redirect default search page slug to the new search page slug.
*/

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

You will need to add "%" before and after "your_search_string" (e.g. %student%) for it to work. You may need to flush the cache if it is a production site with a cache plugin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment