wordpress - 即使在空闲时,Wordpress 插件也会在初始化时继续触发 register_post_type()
问题描述
背景:
我正在使用Wordpress 插件开发人员手册中的样板代码编写一个插件,并想知道为什么某个特定功能会自行触发。我还在add_action()
底部添加了函数并将其连接到init
,我猜这是帖子类型被一遍又一遍地注册的原因。
一个观察和我尝试“修复”它:
看着日志,我注意到这个函数一直在自己触发,但我不知道为什么。经过一番阅读,我尝试在我的函数顶部添加 if 语句,检查DOING_AJAX
,这似乎抑制了 post-type 一遍又一遍地注册。
问题:为什么 Wordpress 会表现出这种行为?
问题:取出函数顶部的 if 语句并让 Wordpress 继续“注册”帖子类型是否安全?
该函数如下所示:
function pluginprefix_setup_post_type() {
// Exit function if doing an AJAX request
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
return;
}
// set up labels
$labels = array(
'name' => 'Products',
'singular_name' => 'Product',
'add_new' => 'Add Product',
'add_new_item' => 'Add Product',
'edit_item' => 'Edit Product',
'new_item' => 'New Product',
'all_items' => 'All Products',
'view_item' => 'View Product',
'search_items' => 'Search Products',
'not_found' => 'No Product Found',
'not_found_in_trash' => 'No Product found in Trash',
'parent_item_colon' => '',
'menu_name' => 'Products',
);
//register post type
error_log('Registering custom post type: my_product');
register_post_type( 'my_product', array(
'labels' => $labels,
'has_archive' => true,
'public' => true,
'supports' => array( 'title', 'editor', 'excerpt', 'custom-fields', 'thumbnail','page-attributes' ),
'taxonomies' => array( 'post_tag', 'category' ),
'exclude_from_search' => false,
'capability_type' => 'post',
'rewrite' => array( 'slug' => 'myproduct' ),
)
);
}
add_action( 'init', 'pluginprefix_setup_post_type' );
解决方案
是的,您可以保留帖子类型注册的原样。init
每次请求页面时,都会在加载 WordPress 系统期间的某个时间点触发该post 类型在运行时包含在$wp_post_types
全局变量中,允许在站点上使用它。因此,在这种情况下,您将拥有始终被注册的帖子类型日志。这很正常。
更直接地回答您的问题:
为什么 Wordpress 会表现出这种行为?
它将帖子类型存储在运行时可用的全局中。这就是 WordPress 的做法。
取出函数顶部的 if 语句并让 Wordpress 继续“注册”帖子类型是否安全?
完全安全且符合预期。
推荐阅读
- javascript - 如何让 cocos creator 触摸监听器
- sequelize.js - graphQL 查询给我空对象作为响应
- vuejs2 - 道具打开时不通过
在新标签中 - typescript - 'FontFace' 仅指一种类型,但在此处用作值
- php - Laravel 5 使用()路径
- binary - 从 Buildroot rootfs 运行可执行文件
- javascript - 在 JavaScript 中获取价值
- excel - 如果 2 对单元格不相等,请在 VBA 中执行某些操作
- db2 - DB2 监控工具 LUW
- java - 如何从 S3 存储桶的各个文件夹中下载与文件名具有相同前缀的多个文件?