sinanisler logo

Adding Custom CSS Block to Block Editor

this code adds a custom css field on your each posts and pages

 

for your custom CSS to work you need to assign a class name to your each block you want to customize otherwise it wont work.

 

and then write your custom code it will work fine.

 

 

add this to your functions.php.

// 1. Add a meta box for custom CSS in the Gutenberg editor
function custom_css_meta_box() {
    add_meta_box(
        'custom_css',
        'Custom CSS',
        'custom_css_meta_box_callback',
        array( 'post', 'page' ),
        'side',
        'high'
    );
}

function custom_css_meta_box_callback( $post ) {
    // Add a nonce for security
    wp_nonce_field( 'save_custom_css', 'custom_css_nonce' );

    // Get the current CSS value if it exists
    $current_css = get_post_meta( $post->ID, '_custom_css', true );

    echo '<textarea class="custom-css-for-posts-pages" style="width:100%; height: 150px;" name="custom_css">' . esc_textarea( $current_css ) . '</textarea>';
}

function save_custom_css( $post_id ) {
    // Verify nonce
    if( ! isset( $_POST['custom_css_nonce'] ) || ! wp_verify_nonce( $_POST['custom_css_nonce'], 'save_custom_css' ) )
        return;

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
        return;

    if( isset( $_POST['custom_css'] ) ) {
        update_post_meta( $post_id, '_custom_css', sanitize_text_field( $_POST['custom_css'] ) );
    }
}

add_action( 'add_meta_boxes', 'custom_css_meta_box' );
add_action( 'save_post', 'save_custom_css' );

// 2. Add the custom CSS to the frontend
function print_custom_css() {
    if( is_singular( array( 'post', 'page' ) ) ) {
        $custom_css = get_post_meta( get_the_ID(), '_custom_css', true );
        if( ! empty( $custom_css ) ) {
            echo '<style type="text/css">' . esc_html( $custom_css ) . '</style>';
        }
    }
}

add_action( 'wp_head', 'print_custom_css' );

// 3. Enqueue the custom CSS in the Gutenberg editor
function enqueue_custom_css_for_gutenberg() {
    if( isset( $_GET['post'] ) ) {
        $post_id = intval( $_GET['post'] );
        $custom_css = get_post_meta( $post_id, '_custom_css', true );
        if( ! empty( $custom_css ) ) {
            wp_add_inline_style( 'wp-codemirror', $custom_css );
        }
    }
}

add_action( 'enqueue_block_editor_assets', 'enqueue_custom_css_for_gutenberg' );

 

 

note:

there 2 missing feature that  Ididnt implement because makes the code more complicated and it has to be plugin wont work like this easy 🙂

1 – it doesn’t support realtime result you need to save and look at front end or refresh the editor to see the result

2 – I was planning to add custom CSS for each block but I think this is much simpler way having only one CSS per page.

maybe I implement another code for both of this features.

Leave the first comment