I’m making a custom theme. It’s a highly specialized theme to make WordPress into like an application rather than a CMS system or blog. For instance, a Dental Office Scheduling System (with CMS and widget capabilities), as an example.
Because my theme needs pretty URLs to work properly, something I really need is for the .htaccess file to be that default that gets created only when someone sets Permalinks to Custom (and then types in something like %postname%). How do I trigger that in WordPress, programmatically, so that it creates this? I mean, I could probably overwrite the file myself during theme activation, but the better thing would be to use the WordPress API for it.
3 Answers
To fully enable permalinks, you also need to ensure that .htaccess is also created. To do that, you need to set an option and flush the rules with a Boolean.
global $wp_rewrite;
//Write the rule
$wp_rewrite->set_permalink_structure('/%postname%/');
//Set the option
update_option( "rewrite_rules", FALSE );
//Flush the rules and tell it to write htaccess
$wp_rewrite->flush_rules( true );
If you use this in a plugin, it needs to be in the init
hook, not the load
hook. If it’s in the load
hook, it will throw an error saying $wp_rewrite
is null.
Important: You should also have a conditional so this is only set once. (You can create an option and check if it’s set, if not then you run this permalink code and set that option)
I also typically check if it’s the admin side and only run it if it is.