我创建了一批自定义ACF gutenberg
块,现在尝试分配预览图像。
问题:让预览图像显示
下图显示了paragraph
一个默认块的组件。
您可以在右侧看到,段落块旁边有一个图像和描述。以下是我的组件当前的显示方式(完整代码将在最后)
如您所见,它说“没有可用的预览”并且没有添加任何描述,即使我已经在代码中定义了两者。
方法:
acf-blocks/blocks.php
<?php
$img_root = "../../src/components";
$hero = array(
'name' => 'hero',
'title' => __('Hero') ,
'description' => __('Hero section') ,
'render_callback' => 'block_render',
'category' => 'formatting',
'icon' => 'admin-comments',
'image' => $img_root . '/hero/hero.png',
'mode' => 'edit',
'keywords' => array(
'hero'
) ,
);
$blocks = [$hero];
return $blocks;
?>
acf-blocks/functions.php
<?php
function block_acf_init(){
$path = get_template_directory().'/inc/acf-blocks/blocks.php';
$blocks = require($path);
foreach($blocks as $block) {
acf_register_block_type($block);
}
}
if( function_exists('acf_register_block_type') ) {
add_action('acf/init', 'block_acf_init');
}
?>
我的文件夹结构如下:
theme
inc
acf-blocks
blocks.php
functions.php
src
components
hero
hero.js
hero.scss
hero.png
不确定为什么我的预览图像不显示?
编辑:
我已经添加了该block_render
功能,但仍然没有成功。这是我当前的functions.php
文件:
<?php
$component_path = "../../src/components" . strtolower($block['title']) . strtolower($block['title']).".js";
function block_render( $block, $content = '', $is_preview = false ) {
$context = get_context();
$context['block'] = $block; // store block values
$context['fields'] = get_fields(); // store field values
$context['is_preview'] = $is_preview;
render($component_path, $context ); // render the block
}
function block_acf_init(){
$path = get_template_directory().'/inc/acf-blocks/blocks.php';
$blocks = require($path);
foreach($blocks as $block) {
acf_register_block_type($block);
}
}
if( function_exists('acf_register_block_type') ) {
add_action('acf/init', 'block_acf_init');
}
?>
编辑2:
<?php
$hero = array(
'name' => 'hero',
'title' => __('Hero'),
'description' => __('Add hero section'),
'render_callback' => 'block_render',
'category' => 'formatting',
'icon' => 'admin-comments',
'mode' => 'edit',
'category' => 'custom',
'post_types' => array(
'page'
),
'keywords' => array(
'hero'
),
'example' => array(
'mode' => 'preview',
'data' => array(
'field' => 'value' // sample data
)
)
);
function block_render($block, $content = '', $is_preview = false)
{
if ($is_preview && !empty($block['data'])) {
echo '<img src="https://i.picsum.photos/id/1021/536/354.jpg?hmac=XeUbyCXoxX2IrSELemo2mRl4zVXzhjFyxtj3GTVZ8xo">';
return;
} elseif ($is_preview) {
echo 'A Hero block using ACF';
return;
}
echo 'A Hero block using ACF.';
}
?>
甚至尝试过:
<?php
function block_render( $block, $content = '', $is_preview = false ) {
if($is_preview):
echo '<img src="https://i.picsum.photos/id/1021/536/354.jpg?hmac=XeUbyCXoxX2IrSELemo2mRl4zVXzhjFyxtj3GTVZ8xo">';
else:
echo '<img src="https://i.picsum.photos/id/1021/536/354.jpg?hmac=XeUbyCXoxX2IrSELemo2mRl4zVXzhjFyxtj3GTVZ8xo">';
endif;
}
?>
在这两种情况下,当尝试显示图像(不是块预览)时,我看到块的 ACF 字段,而不是定义的虚拟图像: