Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.