Support

Account

Home Forums Gutenberg Get Custom Background Color from gutenberg color editor Reply To: Get Custom Background Color from gutenberg color editor

  • Here’s how I’m handling block color settings:

    This function parses the $block attributes and settings:

    
    /**
     * Get an ACF block's color settings.
     *
     * @param array $block The block settings and attributes.
     */
    function get_block_color_attrs( $block = null ) {
        if ( ! $block ) {
            return;
        }
    
        $block_class = null;
        $block_style = null;
    
        if ( $block['backgroundColor'] ) {
            $block_class .= ' has-background has-' . $block['backgroundColor'] . '-background-color ';
        }
    
        if ( $block['textColor'] ) {
            $block_class .= ' has-text-color has-' . $block['textColor'] . '-color ';
        }
    
        if ( $block['style']['color']['background'] ) {
            $block_class .= ' has-background ';
            $block_style .= 'background-color: ' . $block['style']['color']['background'] . ';';
        }
    
        if ( $block['style']['color']['text'] ) {
            $block_class .= ' has-text-color ';
            $block_style .= 'color: ' . $block['style']['color']['text'] . ';';
        }
    
        return array(
            'class' => $block_class,
            'style' => $block_style,
        );
    }
    

    Then I print that information in the block wrapper element:

    
    <div class="<?php echo esc_attr( $block_color_attrs['class'] ); ?>" style="<?php echo esc_attr( $block_color_attrs['style'] ); ?>">
        [...]
    </div>