Coding

How to write htaccess dynamically in WordPress

posted on by - 645 views

The .htaccess is a very important hidden file we normally use in our WordPress installations. It basically tells our server how to behave in certain situations, and things like that. Although I suppose you already know all of this if you ended up here.
One of the problems I had to face while developing a WordPress theme, was finding a way to dynamically edit the htaccess file from WordPress itself. How did I do that? Let’s find out together.

So here’s the problem: we are developing a theme or plugin for WordPress, and we need it to edit the htaccess for our future users. We can’t do it manually, because of course we can’t: we need all to be automated.

How to write htaccess programmatically in WordPress

First of all, let’s go in our functions.php. Here, we can create a new function that will take care of everything for us.

function edit_htaccess(){
  // Edit our htaccess dynamically
  if( !is_multisite() ){
    require_once( ABSPATH . 'wp-admin/includes/file.php' );

    $home_path = get_home_path();
    $htaccess_location = $home_path . '.htaccess';

    $content = array(
      '# THIS IS THE START OF OUR EDIT',
      'This is the first line',
      'Second line', 
      'And, listen up: third line',
      '# AND THIS IS THE END OF OUR EDIT'
    );

    insert_with_markers( $htaccess_location, 'emn_edit', $content );
  }
}

Okay, so: let’s see what we did.

  1. First of all, we check if we’re dealing with a multisite installation: if not, we can go on;
  2. We require a WordPress core file to make everything work properly;
  3. We store in a variable the location of our .htaccess file;
  4. We create an array of contents: each element of it will be a line we want to add in our .htaccess;
  5. We actually do the edit, using insert_with_markers. We’re giving this function three parameters:
    1. The first one is the location of our file;
    2. The second one is the name we want to give to our edit – the way it will be “marked”;
    3. The third is the actual content we want to insert.

Okay! Now we have our function ready to edit the .htaccess file dynamically.

Now we just have one thing left to do: actually call the function when we need it. For that, we will be using a WordPress hook, admin_init, so we can create an action accordingly. So, still in our file functions.php, outside of the function we just created, we can write:

add_action( 'admin_init', 'edit_htaccess' );

That’s it! If we did everything correctly, the next time we load our website we should see our edits in the .htaccess file.