The insert_with_markers() WordPress PHP function inserts an array of strings into a file (such as .htaccess
), placing it between BEGIN and END markers. It replaces existing marked info, retains surrounding data, and creates a file if none exists.
Usage
insert_with_markers( $filename, $marker, $insertion );
Example:
insert_with_markers( '.htaccess', 'MyMarker', array( 'RewriteRule ^example$ example.php' ) );
Parameters
$filename
(string) – Required: Filename to alter.$marker
(string) – Required: The marker to alter.$insertion
(array|string) – Required: The new content to insert.
More information
See WordPress Developer Resources: insert_with_markers()
Examples
Adding custom rewrite rules
This example adds custom rewrite rules to the .htaccess
file.
$rules = array( 'RewriteRule ^old-page$ new-page [R=301,L]', 'RewriteRule ^products/(.*)$ product-details.php?id=$1 [L]' ); insert_with_markers( '.htaccess', 'MyRewriteRules', $rules );
Blocking IPs
This example blocks specific IP addresses using the .htaccess
file.
$blocked_ips = array( 'Deny from 192.168.1.1', 'Deny from 192.168.1.2' ); insert_with_markers( '.htaccess', 'BlockedIPs', $blocked_ips );
Enabling GZIP Compression
This example enables GZIP compression using the .htaccess
file.
$gzip_rules = array( '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' ); insert_with_markers( '.htaccess', 'GZIPCompression', $gzip_rules );
Setting custom headers
This example sets custom headers using the .htaccess
file.
$headers = array( 'Header set X-Content-Type-Options "nosniff"', 'Header set X-Frame-Options "SAMEORIGIN"' ); insert_with_markers( '.htaccess', 'CustomHeaders', $headers );
Setting custom error pages
This example sets custom error pages using the .htaccess
file.
$error_pages = array( 'ErrorDocument 404 /custom-404.html', 'ErrorDocument 500 /custom-500.html' ); insert_with_markers( '.htaccess', 'ErrorPages', $error_pages );