I try to write simple plugin om WordPress. But when I try activate it, I get errow "Notice: Undefined offset: 1" How I fix it? Thank you for your attention.
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');
>Solution :
It looks like you have a couple of issues in your code that are causing the "Notice: Undefined offset: 1" error. Let’s address those issues and correct the code:
Issue with the register_activation_hook() and register_deactivation_hook():
You’re passing the parameters incorrectly for the register_activation_hook() and register_deactivation_hook() functions. You need to provide the hook functions as callbacks in an array. Also, you should call these functions inside the ledproperty class.
Issue with the order of function calls:
You’re trying to use the $ledproperty object before it’s defined. You need to define the object before using it in the activation and deactivation hooks.
Here’s the corrected version of your code:
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();
}
In this corrected code:
I moved the register_activation_hook() and register_deactivation_hook() calls inside the register() method of the ledproperty class.
The __construct() method is used to call the register() method when an object of the ledproperty class is created.
The $ledproperty object is now created after the class definition.
With these changes, your plugin should now activate without any "Undefined offset" error