How to add .htaccess code through a function?

/**
 * Inserts an array of strings into a file (.htaccess ), placing it between
 * BEGIN and END markers. Replaces existing marked info. Retains surrounding
 * data. Creates file if none exists.
 *
 * @param array|string $insertion
 * @return bool True on write success, false on failure.
 */
function add_htaccess($insertion)
{
    $htaccess_file = ABSPATH.'.htaccess';
    return insert_with_markers($htaccess_file, 'MyMarker', (array) $insertion);
}

Notes:

  • $insertion is an array of strings. Each string gets a new line in the file.
  • You should, of course, replace ‘MyMarker’ with your own name. Your content will be inserted in this specified container, leaving the rest of the file alone.
  • This function relies on the insert_with_markers() function which is only loaded in the admin area. You will have to load wp-admin/includes/misc.php manually otherwise.
  • The .htaccess has to be writable in order for this function to work.

Leave a Comment