Last active
July 7, 2022 10:09
-
-
Save rmpel/4d495ef992c1a478ac6e5fa1cc9e460b to your computer and use it in GitHub Desktop.
WPML Multilingual Search slug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/*----------------------------------------- | |
REWRITE SEARCH URLS | |
-----------------------------------------*/ | |
// Redirect ?s=xxx to /search/xxx | |
function redirect_search_url() | |
{ | |
if (is_search() && !empty($_GET['s'])) { | |
wp_redirect(home_url('/' . _x('search' /* default search slug */, 'search url slug', THEME_TEXT_DOMAIN) . '/') . urlencode(get_query_var('s'))); | |
exit(); | |
} | |
} | |
add_action('template_redirect', 'redirect_search_url'); | |
// set the search base so the slug actually works | |
function rewrite_base_urls() | |
{ | |
global $wp_rewrite; | |
// we cannot use _x('search', 'search url slug', THEME_TEXT_DOMAIN) here because we would need to re-build the rewrite rules every page-hit | |
// and that is a big NOPE! | |
$wp_rewrite->search_base = 'search'; /* must be same as default search slug */ | |
} | |
add_action('init', 'rewrite_base_urls'); | |
// but WordPress does not understand the translated slug, so we un-translate it. | |
function pre_patch_request_to_untranslate_search_slug($return) | |
{ | |
$lang = apply_filters('wpml_current_language'); | |
$current_url_prefix = trim(str_replace( site_url(), '', get_bloginfo('url') ), '/'); | |
if ($lang) { | |
$untranslate = array( | |
$current_url_prefix . '/' . _x('search' /* must be same as default search slug */, 'search url slug', THEME_TEXT_DOMAIN) => | |
$current_url_prefix . '/search', /* must be same as default search slug */ | |
); | |
// WordPress uses either one of these, so patch them both | |
$_SERVER['PATH_INFO'] = strtr($_SERVER['PATH_INFO'], $untranslate); | |
$_SERVER['REQUEST_URI'] = strtr($_SERVER['REQUEST_URI'], $untranslate); | |
} | |
return $return; | |
} | |
add_filter('do_parse_request', 'pre_patch_request_to_untranslate_search_slug', -100000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment