Created
June 13, 2023 05:09
-
-
Save krystyna93/c0eeb129d4731a58114745d6d63b4536 to your computer and use it in GitHub Desktop.
WordPress Theme Checking Environment Type Local/Online/Development Mode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function mytheme_enqueue_scripts() { | |
wp_enqueue_style( 'mytheme-style', get_stylesheet_uri() ); | |
// Check if we're in a local development environment or accessing from localhost | |
if ( 'local' === wp_get_environment_type() || in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')) ) { | |
// Enqueue the local development version of the script over HTTP | |
wp_enqueue_script( 'mytheme-scripts', 'http://localhost:8080/bundle.js', array(), '1.0.0', true ); | |
} elseif ( WP_DEBUG ) { | |
// Enqueue the non-optimized version of the script for debugging purposes | |
wp_enqueue_script( 'mytheme-scripts', get_template_directory_uri() . '/js/bundle.js', array(), '1.0.0', true ); | |
} else { | |
// Validate and sanitize user input | |
$bundle_url = filter_input( INPUT_POST, 'bundle-url', FILTER_VALIDATE_URL ); | |
if ( $bundle_url ) { | |
// Escape user-generated content to prevent XSS attacks | |
$escaped_bundle_url = esc_url( $bundle_url ); | |
// Add Content Security Policy header to restrict script sources | |
function mytheme_add_security_headers() { | |
header( "Content-Security-Policy: default-src 'self'; script-src 'self' $escaped_bundle_url;" ); | |
} | |
add_action( 'send_headers', 'mytheme_add_security_headers' ); | |
// Enqueue the production version of the script hosted online with SRI hash over HTTPS | |
$sri_hash = 'sha384-abcdefghijklmnopqrstuvwxyz'; // Replace with your SRI hash | |
wp_enqueue_script( 'mytheme-scripts', $escaped_bundle_url, array(), '1.0.0', true, $sri_hash ); | |
} else { | |
// Handle errors if the URL is invalid or not provided | |
$error_message = 'Invalid bundle URL'; // Default error message | |
if ( ! $bundle_url ) { | |
$error_message = 'Bundle URL is required'; | |
} | |
wp_die( esc_html( $error_message ) ); | |
} | |
} | |
} | |
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_scripts' ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment