2017-06-22 43 views
4

我知道這個問題已經被問過很多次了,但是我沒有找到任何可用於解決問題的工作解決方案或示例。使用PHP動態地在WordPress中使用國家代碼動態地重寫子文件夾

我一直在一個客戶端網站上工作。有兩個類似的網站,一個爲自己的國家,第二個爲其他國家的遊客。

他們的主站點託管在服務器的根目錄中,第二個站點託管在子文件夾中。

現在我想要的是第二個站點的動態網址重寫,它被託管到訪問用戶的國家代碼的子文件夾中。

例如,

http://example.com
http://example.com/subfolder/

是網址。

我想這個http://example.com/subfolder/被改成這個http://example.com/country_code/其中country_code是ISO格式的訪客國家代碼通過php函數。

所以,如果用戶是從美國subfolder,改變爲us,新的URL應該是現在http://example.com/us/

我希望這適用於所有類型的頁面,無論是頁面,文章,類別,標籤還是作者頁面。

如此反覆,http://example.com/subfolder/any-type-of-url/ =>http://example.com/country_code/any-type-of-url/

記住country_code是ISO格式的用戶/訪問者國家代碼。

讓我知道是否有人需要關於此的更多信息。提前致謝。

PS:我試圖用WP中的add_rewrite_rule()函數來實現這個功能。

+0

如何獲取htaccess中的國家代碼? –

+0

@SagarV我沒有在'.htaccess'文件中獲取國家代碼,我有PHP函數,順便說一句,我可以在'.htaccess'文件中獲得國家代碼,看到答案[這裏](https:// stackoverflow。 com/questions/9838344/how-to-redirect-domain-according-to-country-ip-address) –

+0

他們真的會爲每個獨立的國家託管相同的網站嗎?爲什麼不使用qTranslate X或WPML?您可以完全按照所述進行URL重寫。 – Blackbam

回答

0

您可以通過基於用戶國家ISO代碼通過過濾器假裝重寫規則來實現。請在下面找到代碼。

function prepend_default_rewrite_rules($rules) { 

// Prepare for new rules 
$new_rules = []; 

// Set up languages, except default one, get user language code 
$user = get_current_user_id(); 
$language_slugs = (array) get_user_meta($user->ID, 'country_code'); 

// Generate language slug regex 
$languages_slug = '(?:' . implode('/|', $language_slugs) . '/)?'; 


// Set up the list of rules that don't need to be prefixed 
$whitelist = [ 
    '^wp-json/?$', 
    '^wp-json/(.*)?', 
    '^index.php/wp-json/?$', 
    '^index.php/wp-json/(.*)?' 
]; 

// Set up the new rule for home page 
$new_rules['(?:' . implode('/|', $language_slugs) . ')/?$'] = 'index.php'; 

// Loop through old rules and modify them 
foreach ($rules as $key => $rule) { 

    // Re-add those whitelisted rules without modification 
    if (in_array($key, $whitelist)) { 

     $new_rules[ $key ] = $rule; 

    // Update rules starting with^symbol 
    } elseif (substr($key, 0, 1) === '^') { 

     $new_rules[ $languages_slug . substr($key, 1) ] = $rule; 


    // Update other rules 
    } else { 

     $new_rules[ $languages_slug . $key ] = $rule; 

    } 
} 


// Return out new rules 
return $new_rules; 
} 
add_filter('rewrite_rules_array', 'prepend_default_rewrite_rules'); 
+0

它會替代'子文件夾「與用戶國家代碼? –

+0

沒有得到我應該得到的結果。 –

相關問題