Files
plugin-dynamic-theme-style/includes/Functions.php
2025-12-14 15:17:06 +01:00

67 lines
2.0 KiB
PHP

<?php
/**
* Theme Style Darkmode Functions.
* Load and enqueue variant-specific CSS based on system color scheme preference.
*/
namespace LasLie\ThemeStyleDarkmode;
/**
* Load and enqueue variant-specific CSS.
* Reads the style variant from cookie and injects its color palette
* as CSS custom properties.
*
* @return void
*/
function enqueue_variant_styles(): void {
$variant = sanitize_text_field( wp_unslash( $_COOKIE['style_variant'] ?? '' ) );
if ( empty( $variant ) ) {
return;
}
// Sanitize the cookie value and build path to the JSON variant file
$variant = sanitize_file_name( $variant );
$variant_json = get_theme_file_path( "styles/{$variant}.json" );
// Stop if the JSON file does not exist
if ( ! file_exists( $variant_json ) ) {
return;
}
// Read and decode the JSON
$file_content = file_get_contents( $variant_json );
if ( false === $file_content ) {
return;
}
$data = json_decode( $file_content, true );
if ( empty( $data['settings']['color']['palette'] ) ) {
return;
}
// Build CSS variables from the JSON color palette
$css = ":root {\n";
foreach ( $data['settings']['color']['palette'] as $color ) {
$slug = sanitize_title( $color['slug'] ?? '' );
$value = esc_attr( $color['color'] ?? '' );
if ( $slug && $value ) {
$css .= " --wp--preset--color--{$slug}: {$value};\n";
}
}
$css .= "}\n";
// Optional: apply additional top-level text color if available
if ( ! empty( $data['styles']['color']['text'] ) ) {
$text_color = esc_attr( $data['styles']['color']['text'] );
$css .= "body { color: {$text_color}; }\n";
}
// Register an empty style handle and add the generated inline CSS
wp_register_style( 'll-tsd-variant-generated', false );
wp_enqueue_style( 'll-tsd-variant-generated' );
wp_add_inline_style( 'll-tsd-variant-generated', $css );
}
add_action( 'wp_enqueue_scripts', __NAMESPACE__ . '\enqueue_variant_styles', 99 );