Skip to content

Instantly share code, notes, and snippets.

@phlbnks
Last active July 26, 2017 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phlbnks/7624479dba82653be4e9522fac9bc6f8 to your computer and use it in GitHub Desktop.
Save phlbnks/7624479dba82653be4e9522fac9bc6f8 to your computer and use it in GitHub Desktop.
Example snippet showing how to update the WordPress .htaccess file programatically
<?php
/**
* Update .htaccess to whitelist logo when modified in platform settings.
*/
function cc_logo_htaccess() {
// Fire only on Platform Settings options page.
$screen = get_current_screen();
if ( 'cc-configurator_page_cc-settings' === $screen->id && ( $_POST['acf']['field_576c2a5137029'] || $_POST['acf']['field_576c2a9e3702a'] ) ) {
// Store files in an array.
$whitelisted_files = array();
// Get Platform and Client logos.
if ( ! empty( $_POST['acf']['field_576c2a5137029'] ) ) { // cc logo.
$cc_logo = basename( wp_get_attachment_url( $_POST['acf']['field_576c2a5137029'] ) );
$cc_logo_parts = pathinfo( $cc_logo );
$whitelisted_files[] = preg_quote( $cc_logo_parts['filename'] ) . '.*?' . preg_quote( '.' . $cc_logo_parts['extension'] );
}
if ( ! empty( $_POST['acf']['field_576c2a9e3702a'] ) ) { // Client logo.
$client_logo = basename( wp_get_attachment_url( $_POST['acf']['field_576c2a9e3702a'] ) );
$client_logo_parts = pathinfo( $client_logo );
$whitelisted_files[] = preg_quote( $client_logo_parts['filename'] ) . '.*?' . preg_quote( '.' . $client_logo_parts['extension'] );
}
// If we have files, build string and update .htaccess.
if ( ! empty( $whitelisted_files ) ) {
$whitelist = '<FilesMatch "(' . implode( '|', $whitelisted_files ) . ')$">
Satisfy Any
Order allow,deny
Allow from all
Deny from none
</FilesMatch>';
$success = insert_with_markers( trailingslashit( get_home_path() ) . '.htaccess', 'CC Logo whitelist', $whitelist );
if ( false === $success ) {
error_log( 'ERROR:: .htaccess for "' . get_bloginfo( 'name' ) . '" could not be updated with logo whitelist.' );
}
}
}
}
add_action( 'acf/save_post', 'cc_logo_htaccess' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment