Connect with us

How to safely update .htaccess from a WordPress plugin?

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:

Adding your own section is easy. The function takes three parameters:

  1. filename – In this case, the full path of .htaccess
  2. marker – A unique marker that makes sense for your plugin.
  3. insertion – An array with each element being a line of text.

Here is an example:

This would create an addition to .htaccess that looks like this:

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.

Continue Reading
You may also like...
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

More in coding

To Top