2010-04-01 117 views
0

我在我的主題選項面板中有一個設置,允許用戶切換永久鏈接設置以支持友好的URL。我只允許/%postname%/和/%postname%.html作爲選項。自定義固定鏈接切換功能。請檢查這個邏輯

我不想在每次有人訪問網站上的頁面或瀏覽主題選項時觸發htaccess重寫,所以我試圖編碼以避免這種情況。

我在主題選項中有一個名爲$ myTheme_permalinks的輸入字段。默認值爲「/%postname%/」,但用戶也可以將其更改爲「/%postname%.html」

以下是處理此設置的主題選項頂部的代碼。這看起來好聽嗎?

if(get_option('myTheme_permalinks') =="/%postname%/" && get_option('permalink_structure') !== "/%postname%/" || !get_option('myTheme_permalinks')) 
{ 
    require_once(ABSPATH . '/wp-admin/includes/misc.php'); 
    require_once(ABSPATH . '/wp-admin/includes/file.php'); 
    global $wp_rewrite; 
    $wp_rewrite->set_permalink_structure('/%postname%/'); 
    $wp_rewrite->flush_rules(); 
    update_option('permalink_structure','/%postname%/'); 
    update_option('myTheme_permalinks','/%postname%/'); 
} 
else if (get_option('myTheme_permalinks') =="/%postname%.html" && get_option('permalink_structure') !== "/%postname%.html") 
{ 
    require_once(ABSPATH . '/wp-admin/includes/misc.php'); 
    require_once(ABSPATH . '/wp-admin/includes/file.php'); 
    global $wp_rewrite; 
    $wp_rewrite->set_permalink_structure('/%postname%.html'); 
    $wp_rewrite->flush_rules(); 
    update_option('permalink_structure','/%postname%.html'); 
} 

回答

0

您不需要分開代碼塊來添加.html。你可以做一些事情:

$myThemePermalinks = get_option('myTheme_permalinks'); 
if (($myThemePermalinks =="/%postname%/" && get_option('permalink_structure') !== "/%postname%/" || !$myThemePermalinks) || ($myThemePermalinks == "/%postname%.html" && get_option('permalink_structure') !== "/%postname%.html")) { 

    if (preg_match('/\.html$/', $myThemePermalinks)) { 
     $ext = '.html'; 
    } else { 
     $ext = ''; 
    } 

    require_once(ABSPATH . '/wp-admin/includes/misc.php'); 
    require_once(ABSPATH . '/wp-admin/includes/file.php'); 
    global $wp_rewrite; 
    $wp_rewrite->set_permalink_structure('/%postname%/'.$ext); 
    etc..// . 
} 

你不必使用正則表達式,如果你不想,但你明白了。你甚至可以通過使用正則表達式來檢查選項.html來縮短條件。