beblife / acf-gutenberg-blocks
v0.4.2
2020-09-19 15:09 UTC
Requires
- php: >7.0
- wordplate/acf: ^8.5
README
开发者使用高级定制字段PRO功能注册Gutenberg块的优雅方式。
安装
您可以通过composer安装此包
composer require beblife/acf-gutenberg-blocks
定义块
您可以通过创建扩展此包提供的基类块的类来定义自定义块。
通过从基类扩展,您可以轻松定义具有最小配置的自定义块
use GutenbergBlocks\Block; class MyCustomBlock extends Block { protected $name = "custom"; protected $title = "My Custom block"; protected $description = "This is a custom block!"; public function render() { // Render the HTML } }
基类默认配置了一些幕后的事情,以便于使用,但可以轻松更改。以下属性是开箱即用的
protected $name; protected $title; protected $description; protected $keywords = []; protected $category; protected $icon; protected $mode = 'preview'; protected $default_align = ''; protected $align = ['wide', 'full']; protected $allow_mode_switch = true; protected $allow_multiple = true; protected $parent = [];
注册块
要启用自定义块,您需要通过挂钩到acf/init过滤器来注册它们。这允许灵活地定义哪些块应该被启用。
您可以通过传递一个包含类的数组来启用块
add_filter('acf/init', function () { \GutenbergBlocks\Gutenberg::register([ MyCustomBlock::class, ]); });
要自动注册目录中的所有块,可以提供当前主题中的相对路径
add_filter('acf/init', function () { // Registers all blocks in `wp-content/themes/{current_theme}/blocks` \GutenbergBlocks\Gutenberg::register('blocks'); });
定义父块
您可以通过更新块类上的$parent属性来定义一个具有父块块的块。这将导致块在Gutenberg的块列表中被隐藏,但仅作为父块的“子块”可用。
class ChildBlock extends Block { // ... protected $parent = [ ParentBlock::class, ]; }
为了使子块在父块内可选用,您需要在父块上设置
$inner_blocks = true。
配置字段
您可以通过在类上定义一个fields()方法并将它返回一个要添加的字段数组,将字段添加到自定义块中。
此包包括wordplate/extended-acf,以便以简单优雅的方式定义块的字段。请确保阅读文档以了解哪些字段类型可用。
以下是一个如何使用此包定义字段的示例
public function fields() { return [ Text::make('Title') ->required(), Text::make('Body'), Url::make('Link', 'url') ->required() ->instructions('The url that should be displayed.'), ]; }
检索数据
要从定义的字段检索数据,您有几个选项。
// Retrieve all fields as an array $data = $this->data(); // Retrieve only the title $title = $this->get('title'); // Retrieve the body and provide a default value as fallback $body = $this->get('body', 'Hello world!'); // ...
定义类
默认情况下,一些类被添加到包装HTML元素中,以便能够添加通用样式和块的具体样式,并尊重Gutenberg编辑器的对齐和其他输入。
您可以通过定义自己的classes方法来覆盖或扩展添加的类
// Override the default classes protected function classes($block) { return [ 'my-custom-css-class' //... ]; } // Extend the default classes protected function classes($block) { return array_merge(parent::classes($block), [ 'my-custom-css-class', ]); }
请注意,在覆盖默认类时,一些Gutenberg的行为将不再工作,必须从
$block参数中添加,以防止这种情况发生!
渲染块
所有块都需要实现一个render()方法。您如何渲染块由您决定,下面给出了使用WordPress的get_template_part()的示例
public function render() { // Make the data available in our template set_query_var('data', $this->data()); return get_template_part('path-to-my-block-template'); }