tags:

views:

31

answers:

1

I've got a setting in my theme options panel to allow the user to switch the permalinks setting to support friendly URLs. I'm only allowing /%postname%/ and /%postname%.html as options.

I don't want to be triggering an htaccess rewrite everytime someone accesses a page on the site or views theme options, so I'm trying to code this to avoid that.

I've got an input field in theme options that's called $myTheme_permalinks. The default value for this is "/%postname%/" but the user can also change it to "/%postname%.html"

Here's the code at the top of theme options to handle this setting. Does this look sound?

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');
}
A: 

You don't need to separate code blocks just to add the .html. You can do something along the lines of:

$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..// .
}

You don't have to use regex if you don't want to but you get the idea. You could even make the conditional shorter by using regex to check for an option .html.

webbiedave