我的插件在PHP中使用一个呈现回调函数来显示块的内容。块只存储与默认值不同的属性。
有没有一种方法将这些默认值传递给PHP中的呈现回调函数?
我想把一个无意义的默认值放到其中一个属性上,所以如果第一次调用编辑函数,它可以覆盖它们并给所有属性一个默认值。
但在我看来,有更好的方法吗?
发布于 2020-11-26 04:06:23
我也遇到了这个问题,我所做的就是在PHP中定义属性,并使用wp_localize_script传递数组。
然后可以在render_callback中使用use ($var)传递变量。
例如:
$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();
}
] );在你的JS中:
...
registerBlockType( 'my/block', {
title: 'My Block',
icon: 'id',
category: 'layout',
example: {},
attributes: myBlockLocalize.attributes,
// ...
} );
...https://wordpress.stackexchange.com/questions/378827
复制相似问题