如何将ACF Hero Block设为accommodations文章类型的默认必填模块
实现ACF Hero Block作为自定义文章类型默认模块的方案
针对你的需求(新建accommodations类型文章时,默认在顶部添加不可删除的Ferienpark Hero Block),以下是适配ACF Pro 6.0的可行解决方法:
方法1:通过Block Pattern + 编辑器钩子强制默认内容
该方法利用WordPress的Block Pattern功能,配合钩子指定默认编辑器内容,并锁定块防止删除。
步骤1:注册包含Hero块的Block Pattern
在主题的functions.php中添加以下代码:
function register_ferienpark_hero_pattern() { if ( function_exists( 'register_block_pattern' ) ) { register_block_pattern( 'ferienpark/accommodations-default-hero', array( 'title' => '默认Hero模块', 'description' => 'accommodations文章默认顶部Hero块', 'content' => '<!-- wp:acf/hero {"lock":{"remove":true,"move":true}} /-->', 'categories' => array( 'Ferienpark' ), 'post_types' => array( 'accommodations' ), ) ); } } add_action( 'init', 'register_ferienpark_hero_pattern' );
其中"lock":{"remove":true,"move":true}设置块不可删除,但允许调整位置;若不需要移动,可将move改为false。
步骤2:指定accommodations类型的默认编辑器内容
继续在functions.php中添加钩子,确保新建文章时加载预设的Hero块:
function set_accommodations_default_content( $settings, $post ) { if ( $post->post_type === 'accommodations' && empty( $post->post_content ) ) { $settings['defaultEditorContent'] = '<!-- wp:acf/hero {"lock":{"remove":true,"move":true}} /-->'; } return $settings; } add_filter( 'block_editor_settings_all', 'set_accommodations_default_content', 10, 2 );
方法2:通过新建文章钩子直接插入块内容
若方法1不生效,可尝试在文章创建时直接写入块内容到文章主体:
function add_default_hero_to_new_accommodations( $post_id, $post, $update ) { // 仅针对新建的空内容accommodations文章执行 if ( ! $update && $post->post_type === 'accommodations' && empty( $post->post_content ) ) { $hero_block = '<!-- wp:acf/hero {"lock":{"remove":true,"move":true}} /-->'; wp_update_post( array( 'ID' => $post_id, 'post_content' => $hero_block, ) ); } } add_action( 'wp_insert_post', 'add_default_hero_to_new_accommodations', 10, 3 );
关键修正说明
你当前block.json中supports里的"default": true是错误用法——该参数仅控制块是否显示在默认块列表,而非设置默认添加到文章,需删除这一行。
内容的提问来源于stack exchange,提问作者Ramate
相关产品推荐
相关产品推荐

