I need to add the following .htaccess code through a function

    <IfModule mod_deflate.c>
# Insert filters
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/x-httpd-php
AddOutputFilterByType DEFLATE application/x-httpd-fastphp
AddOutputFilterByType DEFLATE image/svg+xml

# Drop problematic browsers
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html

# Make sure proxies don't deliver the wrong content
Header append Vary User-Agent env=!dont-vary
</IfModule>

## Expires Caching ##

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 2 week"
ExpiresByType image/jpeg "access 2 week"
ExpiresByType image/gif "access 2 week"
ExpiresByType image/png "access 2 week"
ExpiresByType text/css "access 2 week"
ExpiresByType application/pdf "access 2 week"
ExpiresByType text/x-javascript "access 2 week"
ExpiresByType application/x-shockwave-flash "access 2 week"
ExpiresByType image/x-icon "access 2 week"
ExpiresDefault "access 2 week"
</IfModule>

## Expires Caching ## 

In my themes function.php

function add_htaccess
{
//the above code to add
}

I just don’t want to add it manually.

3 Answers
3

/**
 * 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 Reply

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