Best approach to change mobile background image and adding its class

  • As I am extending core/group block to add option for setting different image for smaller displays I used render_block_core/group filter to add style tag.
  • I am already adding data-mobile-background-image to each group for its mobile view background image so there is no need for updating it through ID as suggested by Tom J Nowell.

Final Code for setting image using only CSS


add_filter( 'render_block_core/group', array( $this, 'extend_core_group_block' ), 10, 3 );

public function extend_core_group_block( $block_content, $block, $instance ) {

        if ( isset( $instance->parsed_block['attrs']['mobileBackgroundImage'] ) ) {
            $image_path     = ( $instance->parsed_block['attrs']['mobileBackgroundImage'] );
            $block_content .= '
                <style>
                    @media (max-width: 768px){
                        .wp-block-group.has-mobile-background-image[data-mobile-background-image="' . esc_attr( $image_path ) . '"] {
                            background-image: url(' . esc_url( $image_path ) . ') !important;
                        }
                    }
                </style>
            ';
        }

        return $block_content;
    }