由于您已经在使用高级自定义字段,您是否可以使用acf_register_block 而不是独立注册自己的块?这样您就可以在基于 PHP 的模板中从 ACF 访问字段。
这里有一些有用的链接:
此代码取自上面的 ACF 博客文章,并在此处发布以确保上述链接更改的完整性。
注册 ACF 块:
add_action('acf/init', 'my_acf_init');
function my_acf_init() {
// check function exists
if( function_exists('acf_register_block') ) {
// register a testimonial block
acf_register_block(array(
'name' => 'testimonial',
'title' => __('Testimonial'),
'description' => __('A custom testimonial block.'),
'render_callback' => 'my_acf_block_render_callback',
'category' => 'formatting',
'icon' => 'admin-comments',
'keywords' => array( 'testimonial', 'quote' ),
));
}
}
包含块模板的回调函数:
function my_acf_block_render_callback( $block ) {
// convert name ("acf/testimonial") into path friendly slug ("testimonial")
$slug = str_replace('acf/', '', $block['name']);
// include a template part from within the "template-parts/block" folder
if( file_exists( get_theme_file_path("/template-parts/block/content-{$slug}.php") ) ) {
include( get_theme_file_path("/template-parts/block/content-{$slug}.php") );
}
}
块的 HTML:
<?php
/**
* Block Name: Testimonial
*
* This is the template that displays the testimonial block.
*/
// get image field (array)
$avatar = get_field('avatar');
// create id attribute for specific styling
$id = 'testimonial-' . $block['id'];
// create align class ("alignwide") from block setting ("wide")
$align_class = $block['align'] ? 'align' . $block['align'] : '';
?>
<blockquote id="<?php echo $id; ?>" class="testimonial <?php echo $align_class; ?>">
<p><?php the_field('testimonial'); ?></p>
<cite>
<img src="<?php echo $avatar['url']; ?>" alt="<?php echo $avatar['alt']; ?>" />
<span><?php the_field('author'); ?></span>
</cite>
</blockquote>
<style type="text/css">
#<?php echo $id; ?> {
background: <?php the_field('background_color'); ?>;
color: <?php the_field('text_color'); ?>;
}
</style>
这将创建一个基本的推荐块作为一个简单的起点。 ACF 在 Gutenberg 中处理 JavaScript 处理,因此您所要做的就是担心 PHP 方面的事情。
这意味着您可以像我们(ACF 粉丝)一样使用 get_field() 和 the_field() 函数。在不使用这种原生方式的情况下混合 ACF 和 Gutenberg 可能会让人头疼,并且可能需要插件才能通过 WordPress REST API 访问字段。
注意:对 Gutenberg 块的 ACF 支持需要 ACF 5.8 或更高版本。