Skip to content
Advertisement

Creating a WordPress URL Redirect

I’m having a little trouble setting up a WordPress URL redirect.

I’ve designed an ECommerce website with WooCommerce and I’d like to add a search bar that allows me to search filter products in the shop. I’ve added the default WordPress search function and that works fine, however it display all types of content (posts, pages, products, etc.) from across the site.

If I search currently, the URL is as follows:

devsite/?s=searchterm

However, what I need the URL to be in order to display the shop page is this:

devsite/?s=searchterm&post_type=product

I’ve managed to cobble together the following code and placed it in my functions.php file. It nearly works, however, when I press search with the search term the website throws up an error saying it’s being redirected too many times.

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

Please could someone explain why the web page is throwing up the too many redirects error and what I could possibly do to rectify this issue. My PHP knowledge is growing but limited and so any help would be greatly appreciated.

Thanks.

Advertisement

Answer

the problem is in your IF condition, you are checking if the URL contain a get parameter and that get parameter $_GET['s'] is not empty and inside the if function you are redirecting again to a URL that contain a `$_GET[‘s’] with an additional get parameter which is post_type.

Try to do it in the following way, just add another check to check if the post type isn’t specified, its not the best solution but it would solve your problem.

function fb_change_search_url_rewrite() {
    if ( is_search() && ! empty( $_GET['s'] ) && empty($_GET['post_type')) ) {
        wp_redirect( home_url( "?s=" ) . urlencode( get_query_var( 's' ) ) . ( "&post_type=product" ) );
        exit();
    }   
}
add_action( 'template_redirect', 'fb_change_search_url_rewrite' );
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement