You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

激活WordPress插件时出现“Notice: Undefined offset: 1”错误,求修复

修复WordPress插件激活时的"Undefined offset: 1"错误

错误原因

你遇到的Undefined offset: 1错误,是因为register_activation_hook和register_deactivation_hook的回调参数格式错误。这两个函数要求第二个参数是包含回调目标的数组,但你把数组实例和方法名拆成了两个独立参数,导致WordPress解析回调时找不到数组的第二个元素(索引1)。

修复步骤

  1. 将类(或实例)与静态方法名合并为一个回调数组,作为钩子的第二个参数;
  2. 将钩子注册代码移入类存在的判断块内,避免变量未定义的潜在问题。

修复后的完整代码

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__, ['ledproperty', 'activation']);
   register_deactivation_hook(__FILE__, ['ledproperty', 'deactivation']);
}

补充说明

由于activation和deactivation是静态方法,使用['类名', '方法名']的回调格式更规范;如果是普通非静态方法,才需要使用[$实例对象, '方法名']的格式。

内容的提问来源于stack exchange,提问作者Kira Dresst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 16:22:33