Mini plugin ACL CSS

Obsah článku

ACL CSS je plugin pro správu vlastního CSS ve WordPress, které se nachází v sekci Vzhled > Přizpůsobit > CSS. Jeho hlavním účelem je automaticky vytvořit samostatný soubor „custom-style.css“ z CSS Customizeru, deaktivovat vkládaní interního CSS do HTML stránky a tento CSS uložit do samostatného souboru.

Plugin tak umožňuje uživatelům snadnou editaci vlastního CSS přímo z administrace. Nezáleží zda vlastní CSS upravíte přes Vzhled > Přizpůsobit > CSS nebo pomocí tohoto pluginu. Vždy tyto úpravy CSS budou uložené v samostatném souboru.

Plugin využívá CodeMirror editor – výchozí editor kódu ve WordPress, práce s CSS je tak pohodlná.

Kompatibilita

Plugin je navržen pro běžné používání v prostředí WordPress a měl by být kompatibilní s většinou šablon a pluginů.

Dopad na výkon webu

Plugin využije maximálně 0,01 MB z OPCache. Dopad na výkon hostingu je nezměřitelný.

Jak stáhnout?

Plugin stahnete zde: https://ffs.cz/plg/acl-css.zip

 

ACL CSS
<?php
/*
Plugin Name: ACL CSS
Plugin URI: https://ffs.cz
Description: Automatically creates and loads the custom-style.css file with the current CSS from Appearance > Customize > CSS. Saves custom CSS to a separate file and loads it using the standard wp_enqueue_style method. Also allows editing of custom CSS in the admin area.
Version: 1.6
Author: FFS.cz
Author URI: https://ffs.cz/blog/
License: GPLv3
Text Domain: acl
*/

// Load CodeMirror editor
function load_codemirror_editor() {
    $cm_settings['codeEditor'] = wp_enqueue_code_editor(array('type' => 'text/css'));
    wp_localize_script('jquery', 'cm_settings', $cm_settings);

    wp_enqueue_script('wp-theme-plugin-editor');
    wp_enqueue_style('wp-codemirror');
}
add_action('admin_enqueue_scripts', 'load_codemirror_editor');

// Plugin activation function
function automatic_creation_css_activate() {
    // Check for the existence of the custom-style.css file
    $css_file_path = get_stylesheet_directory() . '/custom-style.css';

    // If the file doesn't exist, create it and fill it with the current custom CSS
    if (!file_exists($css_file_path)) {
        $current_custom_css = wp_get_custom_css_post()->post_content;

        // If it doesn't exist in the theme, try to get the global value
        if (empty($current_custom_css)) {
            $current_custom_css = get_option('custom_css_option', '');
        }

        // Create the file and fill it with the current custom CSS
        file_put_contents($css_file_path, $current_custom_css);
    }
}
register_activation_hook(__FILE__, 'automatic_creation_css_activate');

// Function to enqueue the file in the header
function enqueue_custom_style() {
    $css_file_path = get_stylesheet_directory() . '/custom-style.css';
    wp_enqueue_style('custom-style', get_stylesheet_directory_uri() . '/custom-style.css', array(), filemtime($css_file_path), 'all');
}
add_action('wp_enqueue_scripts', 'enqueue_custom_style');

// Called on WordPress initialization
function save_css_to_file_init() {
    // Disable inline CSS insertion
    remove_action('wp_head', 'wp_custom_css_cb', 101);

    // Add a page to the WordPress admin for controlling custom CSS
    add_action('admin_menu', 'custom_css_page');
}

// Called on plugin deactivation
register_deactivation_hook(__FILE__, 'save_css_to_file_deactivate');

// Deactivation function
function save_css_to_file_deactivate() {
    // Delete the custom CSS value on plugin deactivation
    delete_option('custom_css_option');
}

// Add hook for plugin initialization
add_action('init', 'save_css_to_file_init');

// Function to create a page in the WordPress admin
function custom_css_page() {
    add_menu_page(
        'Custom CSS Settings',
        'ACL CSS',
        'manage_options',
        'custom-css-settings',
        'custom_css_page_content',
        'dashicons-admin-generic',
        30
    );
}

// Function for the content of the WordPress admin page
function custom_css_page_content() {
    // Check permissions
    if (!current_user_can('manage_options')) {
        wp_die('You do not have permission to access this page.');
    }

    // Process the form
    if (isset($_POST['custom_css'])) {
        $custom_css = wp_kses_post($_POST['custom_css']); // Save input safely

        // Escape backslashes before quotes
        $custom_css = stripslashes($custom_css);

        // Get the current custom CSS from Appearance > Customize > CSS
        $current_custom_css = wp_get_custom_css_post()->post_content;

        // If it doesn't exist in the theme, try to get the global value
        if (empty($current_custom_css)) {
            $current_custom_css = get_option('custom_css_option', '');
        }

        // Update the custom_css post_type = 'custom_css' entry in the database
        $custom_css_post_id = wp_update_custom_css_post($custom_css);

        if (!is_wp_error($custom_css_post_id)) {
            // Modify the default value for custom CSS
            update_option('custom_css_option', $custom_css);

            // Save custom CSS to the custom-style.css file
            $css_file_path = get_stylesheet_directory() . '/custom-style.css';
            file_put_contents($css_file_path, $custom_css);

            // Add the file to the website header
            wp_enqueue_style('custom-style', get_stylesheet_directory_uri() . '/custom-style.css', array(), filemtime($css_file_path), 'all');

            echo '<div class="updated"><p>Custom CSS has been saved.</p></div>';
        } else {
            echo '<div class="error"><p>Error saving custom CSS.</p></div>';
        }
    }

    // Get the current custom CSS from Appearance > Customize > CSS
    $current_custom_css = wp_get_custom_css_post()->post_content;

    // If it doesn't exist in the theme, try to get the global value
    if (empty($current_custom_css)) {
        $current_custom_css = get_option('custom_css_option', '');
    }
    ?>
    <div class="wrap">
        <h2>Current custom CSS from Appearance > Customize > CSS</h2>
        <?php display_custom_css_file_size(); // Display the current custom CSS file size ?>
        <style>
            .CodeMirror {
                border: 1px solid #eee;
                height: auto;
            }

            .CodeMirror-scroll {
                overflow-y: auto;
                overflow-x: auto;
            }
        </style>
        <form method="post" action="">
            <textarea name="custom_css" rows="20" cols="70" style="width:100%" id="fancy-textarea"><?php echo esc_textarea($current_custom_css); ?></textarea><br><br>
            <input type="submit" class="button button-primary" value="Save">
        </form>

        <script type="text/javascript">
            jQuery(document).ready(function ($) {
                var editor = wp.codeEditor.initialize($('#fancy-textarea'), cm_settings);

                // Resize the editor when the content changes
                editor.on('change', function () {
                    var height = editor.doc.height();
                    editor.setSize(null, Math.max(height, 400));
                });
            });
        </script>
    </div>
    <?php
}

// Function to display the current custom CSS file size
function display_custom_css_file_size() {
    $file_size = get_custom_css_file_size();
    echo '<p>Custom CSS File Size: ' . $file_size . '</p>';
}

// Function to get the custom CSS file size
function get_custom_css_file_size() {
    $css_file_path = get_stylesheet_directory() . '/custom-style.css';

    // Check if the file exists
    if (file_exists($css_file_path)) {
        $file_size = filesize($css_file_path);

        // If the size is less than 1024 bytes, display in bytes
        if ($file_size < 1024) {
            return $file_size . ' bytes';
        } else {
            // If the size is greater than 1024 bytes, convert to kilobytes with precision to 2 decimal places
            $file_size_kb = round($file_size / 1024, 2);
            return $file_size_kb . ' KB';
        }
    } else {
        // If the file doesn't exist, return an appropriate message
        return 'File not found';
    }
}

// Filter to prevent inline CSS insertion
function disable_inline_css($value, $option, $default) {
    if ($option === 'wp_css_inline') {
        return '';
    }
    return $value;
}

// Add filters
add_filter('pre_option_wp_css_inline', 'disable_inline_css', 10, 3);
add_filter('pre_update_option_wp_css_inline', 'disable_inline_css', 10, 3);
?>