我正试图按照指南使用OOP开发我的第一个Wordpress插件。到目前为止,我已经逐字逐句地关注了这个问题,但我仍在努力解决这个问题,我无法重写我想象中的URL。
这是我正在使用的代码。。。
class BookItNow
{
function __construct()
{
add_action(\'init\', $this->custom_post_type());
}
function activate()
{
$this->custom_post_type();
flush_rewrite_rules();
}
function register()
{
add_action(\'admin_enqueue_scripts\', array($this, \'enqueue\'));
}
function deactivate()
{
flush_rewrite_rules();
}
function custom_post_type()
{
register_post_type(\'bookings\', [\'public\' => true, \'label\' => \'Bookings\']);
}
function enqueue()
{
wp_enqueue_style(\'style\', plugins_url(\'/assets/style.css\', __FILE__));
}
}
if (class_exists(\'BookItNow\')) {
$book = new BookItNow();
$book->register();
}
register_activation_hook(__FILE__, array($book, \'activate\'));
register_deactivation_hook(__FILE__, array($book, \'deactivate\'));
register_uninstall_hook(__FILE__, array($book, \'uninstall\'));
这就是我犯的错误
Uncaught Error: Call to a member function add_rewrite_tag() on null. 删除
$this->custom_post_type() 删除此问题,所以我不知道。任何帮助都将不胜感激。
最合适的回答,由SO网友:locomo 整理而成
尝试以下更改:
1) 要在使用类而不是只传递函数名来构建插件或主题时使用add\\u action(),需要传递一个数组,其中引用类($this)和可调用函数(\'custom\\u post\\u type\')
function __construct()
{
add_action(\'init\', array( $this, \'custom_post_type\' ) );
}
2)原始的“activate”方法称为“custom\\u post\\u type”,建议在插件激活时只需调用一次。但是,为了正确注册自定义post类型,每次加载Wordpress时都需要调用此方法,这就是为什么它被添加到“init”挂钩中的原因。在activate方法中调用它真的没有意义,所以我删除了它。
function activate()
{
flush_rewrite_rules();
}