0

My plugin uses a render callback function in PHP, to display the content of a block. The block only stores the attributes that differ from the default values.

Is there a way to pass those default values into the render callback function in PHP?

I was thinking about putting a nonsense default value to one of the attributes, so if the edit function gets called for the first time it can overwrite them and give all of the attributes a default value.

But this seems to me rather hacky, is there a better way to do that?

1 Answer 1

0

I also had this problem, and what I did is to define the attribute inside PHP and use wp_localize_script to pass down the array.

Then you can pass in the variable in render_callback using use ($var)

For example:

$js = get_stylesheet_directory_uri() . '/assets/js';
$css= get_stylesheet_directory_uri() . '/assets/css';

$default_attributes = [
  'alignment' => [ 'type' => 'string', 'default' => 'left' ],
  'iconPosition' => [ 'type' => 'string', 'default' => 'left' ],

  'textColor' => [ 'type' => 'string', 'default' => 'var(--text)' ],
  'bgColor' => [ 'type' => 'string', 'default' => 'var(--textInvert)' ],
];


wp_register_script( 'my-block', $dist . '/my-block.js', [ 'wp-blocks', 'wp-dom' ] , null, true );
wp_register_style( 'my-block', $dist . '/my-block.css', [ 'wp-edit-blocks' ] );

wp_localize_script( 'my-block', 'myBlockLocalize', [ 'attributes' => $default_attributes ] );

register_block_type( 'my/block', [
  'editor_style' => 'my-block',
  'editor_script' => 'my-block',
  'render_callback' => function( $atts, $inner_blocks = null ) use ( $default_attributes ) {
      $default_values = array_map( function( $a ) {
        return $a['default'] ?? '';
      }, $default_attributes );

      $atts = wp_parse_args( $atts, $default_values );

      ob_start();
      // output the HTML here, I believe you can use get_template_parts()
      return ob_get_clean();
    }
] );

In your JS:

...

registerBlockType( 'my/block', {
  title: 'My Block',
  icon: 'id',
  category: 'layout',
  example: {},
  attributes: myBlockLocalize.attributes,
  
  // ...

} );

...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.