coding
How to safely update .htaccess from a WordPress plugin?
Sometimes during plugin development you may need to make an update to the .htaccess file. This can be rather daunting when you start to think about the unknown. What is currently there? Does the file exist? Can I write to it? Luckily WordPress has a builtin function to help assist with this, “insert_with_markers()” in misc.php.
The function relies on markers in the .htaccess to identify which part it needs to update. For example the WordPress updates for permalinks has “WordPress” as the marker and looks something like:
1
2
3
4
5
6
7
8
|
# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !–f
RewriteCond %{REQUEST_FILENAME} !–d
RewriteRule . /index.php [L]
# END WordPress
|
Adding your own section is easy. The function takes three parameters:
- filename – In this case, the full path of .htaccess
- marker – A unique marker that makes sense for your plugin.
- insertion – An array with each element being a line of text.
Here is an example:
1
2
3
4
5
6
7
|
// Get path to main .htaccess for WordPress
$htaccess = get_home_path().“.htaccess”;
$lines = array();
$lines[] = “RewriteBase /foobar”;
insert_with_markers($htaccess, “MyPlugin”, $lines);
|
This would create an addition to .htaccess that looks like this:
1
2
3
|
# BEGIN MyPlugin
RewriteBase /foobar
# END MyPlugin
|
One important point to mention is that get_home_path() and insert_with_markers() are only available while the plugin is executing in the admin interface. For example your activation function for you plugin would be a great place to put this. During deactivation, sending a blank array for the insertion parameter will remove the configuration.