Theme Integration and Customization

Theme Integration and Customization

WordPress themes often require special CSP considerations due to their customization options and dynamic styling.

// Theme-specific CSP handler
class WP_CSP_Theme_Handler {
    public function __construct() {
        add_action('wp_head', [$this, 'add_theme_csp_meta'], 1);
        add_filter('wp_csp_directives', [$this, 'add_theme_directives']);
    }
    
    public function add_theme_directives($directives) {
        $theme = wp_get_theme();
        
        // Handle customizer inline styles
        if (is_customize_preview()) {
            $directives['style-src'][] = "'unsafe-inline'";
            $directives['script-src'][] = "'unsafe-eval'";
        }
        
        // Popular theme frameworks
        if ($this->is_genesis_theme()) {
            $directives['script-src'][] = "'unsafe-inline'";
        }
        
        if ($this->is_divi_theme()) {
            $directives['script-src'][] = "'unsafe-eval'";
            $directives['style-src'][] = "'unsafe-inline'";
        }
        
        // Add theme customizer fonts
        $custom_fonts = get_theme_mod('custom_fonts', []);
        foreach ($custom_fonts as $font_url) {
            $parsed = parse_url($font_url);
            if ($parsed['host']) {
                $directives['font-src'][] = 'https://' . $parsed['host'];
            }
        }
        
        return $directives;
    }
    
    private function is_genesis_theme() {
        return function_exists('genesis');
    }
    
    private function is_divi_theme() {
        $theme = wp_get_theme();
        return strpos($theme->get('Name'), 'Divi') !== false;
    }
}