我试着用WordPress编写简单的插件.但当我try 激活它时,我得到了错误的"通知:未定义的偏移:1"我如何修复它?谢谢大家的关注.

if (!defined('ABSPATH')) {
   die;
}

class ledproperty {

   public function register() {
      add_action('init', [$this, 'custom_post_type']);
   }

   public function custom_post_type() {
      register_post_type('property', 
      array(
         'public' => true,
         'has_archive' => true,
         'rewrite' => array('slug' => 'properties'),
         'label' => 'Property',
         'supports' => array('title', 'editor', 'thumbnail')
      
      ));
   }

   static function activation() {
      flush_rewrite_rules();
   }
   static function deactivation() {
      flush_rewrite_rules();
   }
}
if(class_exists('ledproperty')) {
   $ledproperty = new ledproperty();
   $ledproperty -> register();
}

register_activation_hook(__FILE__, array($ledproperty), 'activation');
register_deactivation_hook(__FILE__, array($ledproperty), 'deactivation');

推荐答案

看起来您的代码中有几个问题导致了"通知:未定义的偏移量:1"错误.让我们解决这些问题并更正代码:

REGISTER_ACTIVATION_HOOK()和REGISTER_DEACTIVATION_HOOK()的问题: 您错误地传递了REGISTER_ACTIVATION_HOOK()和REGISTER_DEACTIVATION_HOOK()函数的参数.您需要将挂钩函数作为数组中的回调函数提供.此外,您应该在ledProperty类中调用这些函数.

函数调用顺序问题: 您试图在定义$ledProperty对象之前使用它.在激活和停用挂钩中使用对象之前,您需要定义该对象.

以下是您的代码的更正版本:

if (!defined('ABSPATH')) {
   die;
}

class ledproperty {

   public function __construct() {
      $this->register();
   }

   public function register() {
      add_action('init', [$this, 'custom_post_type']);
      register_activation_hook(__FILE__, [$this, 'activation']);
      register_deactivation_hook(__FILE__, [$this, 'deactivation']);
   }

   public function custom_post_type() {
      register_post_type('property', 
      array(
         'public' => true,
         'has_archive' => true,
         'rewrite' => array('slug' => 'properties'),
         'label' => 'Property',
         'supports' => array('title', 'editor', 'thumbnail')
      
      ));
   }

   public function activation() {
      flush_rewrite_rules();
   }

   public function deactivation() {
      flush_rewrite_rules();
   }
}

if(class_exists('ledproperty')) {
   $ledproperty = new ledproperty();
}

在此更正的代码中:

我将注册_激活_挂钩()和注册_停用_挂钩()调用移到了ledProperty类的注册()方法中.

在创建ledProperty类的对象时,使用__Construction()方法调用Register()方法.

现在,在类定义之后创建了$ledProperty对象. 有了这些更改,您的插件现在应该会激活,不会出现任何"未定义的偏移量"错误

Php相关问答推荐

管理员订单列表中的自定义列与WooCommerce 8.6.1一起消失

将变体设置字段添加到WooCommerce中的特定变量产品

Laravel;Composer安装突然返回选项快捷方式不能为空.

允许在WooCommerce管理员优惠券列表中显示自定义优惠券类型

当配置的URL为空时禁用Laravel Slack日志(log)记录

如何在Livewire 3 Form类中做依赖注入?

对表示大小的值后缀进行自定义排序(XXS、XS、S、M、L、XL、XXL)

如何在codeigniter中将order_by RAND与下面的代码一起使用

关于Laravel缓存出现的错误

如果 Select 的县不是store 所在的县,如何隐藏本地自提?

使用动态地址和动态文件创建zip文件并获取zip文件链接

Woocommerce的数量和价格条件

在 Botiga 主题模板中添加复选框到政策行.Woocommerce

WooCommerce checkout 流程中基于所选选项添加自定义费用

在WooCommerce我的账户单个订单页面中添加订单商品部分和按钮

WooCommerce - 调用功能ID不正确.不应直接访问订单属性

.htaccess环境变量条件不被判断

Shopware 6:无法在新的自定义插件中保存关联字段(媒体)

Laravel 测试 assertJsonMissing 不适用于唯一的键.为什么?

多排序子数组 - 包含范围数据的子数组