ACF如何实现不加载WordPress默认内容编辑器

ACF(Advanced Custom Fields)通过多种技术手段实现选择性加载或不加载WordPress默认内容编辑器,以下是其核心实现机制:

一、编辑器移除的核心方法

1. 通过remove_post_type_support函数

// ACF在初始化时会检查字段组配置
add_action('init', function() {
if (acf_get_field_groups(array('post_id' => 'options_page'))) {
remove_post_type_support('page', 'editor');
remove_post_type_support('post', 'editor');
}
}, 99); // 低优先级确保其他插件已加载

2. 条件性移除(基于字段组位置规则)

add_action('current_screen', function($screen) {
$field_groups = acf_get_field_groups(array(
'post_id' => $screen->id,
'post_type' => $screen->post_type
));

if (!empty($field_groups)) {
remove_post_type_support($screen->post_type, 'editor');
}
});

二、ACF的完整实现流程

1. 字段组配置检测

2. 编辑器移除决策

// ACF核心代码简化版
function acf_maybe_remove_editor() {
global $post;

// 1. 获取当前界面相关字段组
$field_groups = acf_get_field_groups(array(
'post_id' => $post ? $post->ID : false,
'post_type' => get_current_screen()->post_type
));

// 2. 检查是否有字段组要求移除编辑器
foreach ($field_groups as $group) {
if (isset($group['hide_on_screen']) &&
in_array('the_content', $group['hide_on_screen'])) {
remove_post_type_support(get_current_screen()->post_type, 'editor');
break;
}
}
}
add_action('load-post.php', 'acf_maybe_remove_editor');
add_action('load-post-new.php', 'acf_maybe_remove_editor');

三、技术细节解析

1. 字段组配置存储

ACF在字段组的hide_on_screen设置中存储需要隐藏的界面元素:

// 字段组配置示例
array(
'hide_on_screen' => array(
'the_content', // 移除内容编辑器
'excerpt', // 移除摘要编辑器
'discussion', // 移除讨论模块
'comments', // 移除评论模块
'revisions', // 移除修订版本
'slug', // 移除别名编辑
'author', // 移除作者选择
'format', // 移除文章格式
'page_attributes', // 移除页面属性
'featured_image', // 移除特色图片
'categories', // 移除分类目录
'tags' // 移除标签
)
)

2. 多场景适配机制

ACF会根据不同上下文智能判断:

  • ​文章类型编辑页​​:通过current_screen挂钩检测
  • ​选项页​​:直接禁用编辑器
  • ​快速编辑​​:保留编辑器功能
  • ​前端提交表单​​:不加载编辑器资源

四、资源加载优化

1. 选择性加载编辑器资源

add_action('admin_enqueue_scripts', function() {
$load_editor = true;

// 检查是否需要编辑器
if (acf_get_field_groups(array('post_id' => get_the_ID()))) {
$load_editor = false;
}

// 动态加载资源
if (!$load_editor) {
wp_dequeue_script('editor');
wp_dequeue_style('editor-buttons');
}
});

2. 与古腾堡编辑器的兼容

// 禁用古腾堡编辑器
add_filter('use_block_editor_for_post_type', function($enabled, $post_type) {
if (acf_disable_editor($post_type)) {
return false;
}
return $enabled;
}, 10, 2);

五、自定义实现方案

1. 完全禁用内容经典编辑器

// 在主题functions.php中添加
add_action('init', function() {
remove_post_type_support('post', 'editor');
remove_post_type_support('page', 'editor');
});

2. 基于ACF字段的条件禁用

add_action('current_screen', function($screen) {
if ($screen->post_type === 'product' &&
acf_get_field('product_custom_layout')) {
remove_post_type_support('product', 'editor');
}
});

ACF通过这种精细化的编辑器控制机制,实现了内容管理界面的高度定制化,使开发者能够创建完全符合项目需求的编辑环境。

我爱主题网 自2012
主题:260+ 销售:1000+
兼容浏览器

电话咨询

7*12服务咨询电话:

1855-626-3292

微信咨询