我使用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 v5.9.8
发布于 2021-07-18 20:25:46
这是get_field:https://www.advancedcustomfields.com/resources/get_field/的文档
注意,有一个可选的第二个参数。
$post_id (混合)(可选)保存值的post ID。默认为当前职位。
因此,如果您的函数在一个地方工作,而不是在另一个地方工作,那么这两个页面之间存在环境差异。有可能在UI上没有在技术上选择post,在这种情况下,您需要传递您想要得到的帖子的id。
https://stackoverflow.com/questions/68432313
复制相似问题