Php 自定义永久链接切换功能。请检查这个逻辑

Php 自定义永久链接切换功能。请检查这个逻辑,php,wordpress,Php,Wordpress,我的主题选项面板中有一个设置,允许用户切换永久链接设置以支持友好的URL。我只允许/%postname%/和/%postname%.html作为选项 我不想每次有人访问站点上的页面或查看主题选项时都触发htaccess重写,所以我尝试编写代码以避免这种情况 我在主题选项中有一个名为$myTheme\u permalinks的输入字段。默认值为“/%postname%/”,但用户也可以将其更改为“/%postname%.html” 下面是主题选项顶部处理此设置的代码。这听起来像吗 if(get_o

我的主题选项面板中有一个设置,允许用户切换永久链接设置以支持友好的URL。我只允许/%postname%/和/%postname%.html作为选项

我不想每次有人访问站点上的页面或查看主题选项时都触发htaccess重写,所以我尝试编写代码以避免这种情况

我在主题选项中有一个名为$myTheme\u 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');
}

您不需要仅仅为了添加.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..// .
}
如果你不想使用正则表达式,你不必使用正则表达式,但是你已经有了这个想法。您甚至可以通过使用regex检查option.html来缩短条件