Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive className with ServerSideRender of Gutenberg?

I'm trying to render a block from PHP with ServerSideRender as follows:

js file:

/**
 * WordPress dependencies
 */
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { ServerSideRender } = wp.components;

/**
 * Internal dependencies
 */
import icons from './../../utils/icons';

registerBlockType( 'name/blockname', {
  title: __( 'blockname' ),
  description: __( 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.' ),
  keywords: [ __( 'recent post' ) ],
  icon: icons.block,
  category: 'xyz',

  edit: ( props ) => {
    const {
      className,
      attributes,
    } = props;

    return (
      <ServerSideRender
        block="name/blockname"
        attributes={ attributes }
        className={ className }
      />
    );
  },

  save: () => {
    return null;
  },
} );

php file:


register_block_type( '.../blockname', array(
   'attributes'      => array(
      'className'    => array(
         'type'      => 'string',
      ),
   ),
   'render_callback' => 'render_block',
) );

function render_block( $attr, $content ) {
    return 'txt';
}

Render:

   <div>txt</div>

Expected:

   <div class="wp-block-name-blockname">txt</div>

Everything seems to work correctly but the div with the class name is not being rendered.

Any suggestion to fix this? thank you in advance.

like image 677
Jhon Escobar Avatar asked Dec 19 '25 13:12

Jhon Escobar


1 Answers

You want to change your render_block function to:

function render_block( $attr, $content ) {
  return sprintf(
    '<div class="wp-block-name-blockname %1$s">txt</div>',
    esc_attr( $attr['className'] )
  );
}

Also see the official tutorial of creating dynamic blocks.

like image 60
niklas Avatar answered Dec 21 '25 03:12

niklas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!