$meta ) { $formats[] = array( 'value' => $slug, 'label' => $meta['label'], ); } foreach ( self::attributes() as $key => $spec ) { $defaults[ $key ] = $spec['default']; } wp_localize_script( 'bcgn-block', 'bcgnBlock', array( 'formats' => $formats, 'attributes' => self::attributes(), 'defaults' => $defaults, ) ); register_block_type( 'barcodegen/barcode', array( 'api_version' => 2, 'editor_script' => 'bcgn-block', 'render_callback' => array( __CLASS__, 'render' ), 'attributes' => self::attributes(), 'supports' => array( 'align' => array( 'left', 'center', 'right' ), ), ) ); } /** * Block attributes, mirroring the shortcode. * * @return array> */ public static function attributes() { return array( 'format' => array( 'type' => 'string', 'default' => BCGN_Settings::get( 'default_format' ), ), 'value' => array( 'type' => 'string', 'default' => '', ), 'scale' => array( 'type' => 'number', 'default' => (float) BCGN_Settings::get( 'scale' ), ), 'height' => array( 'type' => 'number', 'default' => (int) BCGN_Settings::get( 'height' ), ), 'text' => array( 'type' => 'boolean', 'default' => (bool) BCGN_Settings::get( 'text' ), ), 'bar_color' => array( 'type' => 'string', 'default' => BCGN_Settings::get( 'bar_color' ), ), 'bg_color' => array( 'type' => 'string', 'default' => BCGN_Settings::get( 'bg_color' ), ), ); } /** * Server side render callback. * * @param array $attributes Block attributes. * @return string */ public static function render( $attributes ) { $attributes = is_array( $attributes ) ? $attributes : array(); $value = isset( $attributes['value'] ) ? trim( (string) $attributes['value'] ) : ''; if ( '' === $value ) { return sprintf( '

%s

', esc_html__( 'Barcodegen: add a value in the block settings to generate a barcode.', 'barcodegen' ) ); } $args = array( 'scale' => isset( $attributes['scale'] ) ? $attributes['scale'] : BCGN_Settings::get( 'scale' ), 'height' => isset( $attributes['height'] ) ? $attributes['height'] : BCGN_Settings::get( 'height' ), 'text' => ! empty( $attributes['text'] ), 'bar_color' => isset( $attributes['bar_color'] ) ? $attributes['bar_color'] : '#000000', 'bg_color' => isset( $attributes['bg_color'] ) ? $attributes['bg_color'] : 'transparent', 'class' => 'bcgn-barcode', ); $svg = BCGN_Barcode::svg( isset( $attributes['format'] ) ? $attributes['format'] : 'code128', $value, $args ); if ( is_wp_error( $svg ) ) { return sprintf( '

%s %s

', esc_html__( 'Barcodegen:', 'barcodegen' ), esc_html( $svg->get_error_message() ) ); } if ( BCGN_Settings::get( 'credit' ) ) { $svg .= BCGN_Shortcode::credit_markup(); } return $svg; } }