[Assigned] Change Search URL Slug for different language
This is the technical support forum for WPML - the multilingual WordPress plugin.
Everyone can read, but only WPML clients can post here. WPML team is replying on the forum 6 days per week, 22 hours per day.
Elementor users - please update WPML to the latest version to maintain compatibility. More details here - https://wpml.org/changelog/2024/12/wpml-4-6-15-critical-update-for-elementor-sites/
Hintergrund des Themas:
I am trying to customize my search page on my WordPress site. I have rewritten the default search URL (/?s=) with a custom function in the theme to redirect to /search/. The function I used is: function custom_search_url_rewrite() { if ( is_search() && ! empty( $_GET['s'] ) ) { wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) ); exit(); } } add_action( 'template_redirect', 'custom_search_url_rewrite' ).
Die Symptome:
I need a variant of the custom search URL for the German page at /de/suche/.
Fragen:
Do you have any tips on how to create a variant for the German page at /de/suche/?
Please note that while we will do our best to help you move your project forward custom work is outside of our support's scope.
If further help is required for custom work, we recommend reaching out to one of our vetted 3rd party developers
The following code allowed me to achieve the desired result
function custom_search_url_rewrite() {
if ( is_search() && ! empty( $_GET['s'] ) ) {
// Check if WPML is active and a language code is defined
$current_lang = defined('ICL_LANGUAGE_CODE') ? ICL_LANGUAGE_CODE : '';
// If you want to handle default language differently (omitting its code),
// uncomment and adjust this section:
$default_lang = apply_filters( 'wpml_default_language', null );
if ( $current_lang && $current_lang === $default_lang ) {
// // Default language: no language code in the URL
$lang_prefix = '';
} else {
// // Secondary language: include the language code
$lang_prefix = $current_lang ? $current_lang . '/' : '';
}
// If you want to always show the language code regardless of default language:
// $lang_prefix = $current_lang ? $current_lang . '/' : '';
// Redirect to the language-specific search URL
wp_redirect( home_url( "/" . $lang_prefix . "search/" ) . urlencode( get_query_var( 's' ) ) );
exit();
}
}
add_action( 'template_redirect', 'custom_search_url_rewrite' );
You can also test it here by using the search at the top: hidden link
NOTE: Please note that this code is not tested by our team and provided at the discretion of the supporter as it's outside our support's scope.
Also, before using any custom code provided by us please make sure to have a working backup in pleasee.