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
Click to comment

Leave a Reply

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

More in coding

About Me:

Szabi Kisded

Hey there, I'm Szabi. At 30 years old, I quit my IT job and started my own business and became a full time WordPress plugin developer, blogger and stay-at-home dad. Here I'm documenting my journey earning an online (semi)passive income. Read more

Sign up for my newsletter and get the YouTube Caption Scraper WordPress plugin for free
(worth 29$)!

All My Plugins In A Bundle:

My AutoBlogging Plugins:

My Online Courses:

A Theme I Recommend:

Featured Posts:

To Top