WordPress how to encode the searched URL

Viewed 226

I want to make a search URL look like this:

example.com/search/search+query?post_type=product.

I have tried many methods including this:

wp_redirect( home_url( "/search/?s=" ) . urlencode( get_query_var( 's' ) . "&post_type=" . urlencode( get_query_var( 'post_type' ) ) );

and this:

wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ). "?post_type=". urlencode( get_query_var( 'post_type' ) ) ) );

but the result I am getting:

example.com/search/search+query%3Fpost_type%3Dproduct

What should I do?

2 Answers

The following snippet will do the trick for you!

$decoded_url = urldecode('example.com/search/search+query%3Fpost_type%3Dproduct');

echo $decoded_url;

And the result would be:

example.com/search/search query?post_type=product 

urlencode_deep( mixed $value )

Navigates through an array, object, or scalar, and encodes the values to be used in a URL.

$value - (mixed) (Required) The array or string to be encoded.

function urlencode_deep( $value ) {
    return map_deep( $value, 'urlencode' );
}
Related