【发布时间】:2021-09-26 15:13:24
【问题描述】:
我使用 ACF acf_register_block_type(); 函数构建了一个自定义块
它在 WordPress 仪表板(块编辑器)中运行良好,它显示了字段数据,一切都很好。
但在前端(查看页面)中,字段为 NULL
有关如何在前端显示字段数据的任何帮助??
functions.php 代码:
add_action('acf/init', 'my_acf_init_block_types');
function my_acf_init_block_types()
{
// Check function exists.
if (function_exists('acf_register_block_type')) {
// register a hero block.
acf_register_block_type(array(
'name' => 'banner',
'title' => __('Banner'),
'description' => __('A custom hero block.'),
'render_callback' => 'my_acf_block_render_callback',
'category' => 'home-sections',
'icon' => 'cover-image',
'keywords' => array('basic', 'banner')
));
}
}
function my_acf_block_render_callback($block)
{
// convert name ("acf/hero") into path friendly slug ("hero")
$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/blocks/content-{$slug}.php"))) {
include(get_theme_file_path("/template-parts/blocks/content-{$slug}.php"));
}
}
function wpdocs_mytheme_block_styles()
{
wp_enqueue_style('admin-css', get_stylesheet_directory_uri() . '/build/css/styles.min.css', '', '0.0.3');
wp_enqueue_script('admin-js', get_template_directory_uri() . '/build/js/scripts.min.js', array('jquery'), '0.0.3', true);
}
add_action('enqueue_block_editor_assets', 'wpdocs_mytheme_block_styles')
banner.php 代码:
<?php
$title = get_field('main_title');
$img = get_field('background_image');
$button = get_field('button');
?>
<section id="banner-section" style=" background-image:linear-gradient( rgba(67, 74, 122, 0.5), rgba(67, 74, 122, 0.5) ), url('<?= $img['url']; ?>');">
<div class="container">
<div class="row justify-content-center">
<div class="col-12 col-lg-10 text-center">
<h1 class="basic-slider-heading"> <?php echo $title ?> </h1>
<?php
if ($button) :
$button_url = $button['url'];
$button_title = $button['title'];
$button_target = $button['target'] ? $button['target'] : '_self';
?>
<button class="btn btn-shadow-malibu btn-bg-malibu-gradient bg-malibu-accent">
<a href="<?= $button_url ?>" target="<?= $button_target; ?>"><?= $button_title ?></a>
</button>
<?php endif; ?>
</div>
</div>
</div>
</section>
var_dump( get_field('main_title'));
注意:我使用的是 WordPress v5.7.2 和 ACF PRO v5.9.8
【问题讨论】:
-
我使用类似的代码遇到了完全相同的问题。根据我对块编辑器中使用的 ACF 块的理解,没有使用 $post_id。在这种情况下,是同一个页面,只是前端和后端渲染的区别。
标签: php wordpress advanced-custom-fields wordpress-gutenberg