如何在我的 OOP 插件中添加自定义 post 类型?
How to add a custom post type in my OOP plugin?
我需要为插件创建自定义 post 类型。好吧,我决定以面向对象的方式创建插件,所以基本上我使用 Devin Vinson 的 WordPress-Plugin-Boilerplate 作为起点。
我见过许多插件在主插件文件中添加自定义 post 类型,如下所示:
add_action( 'init', 'create_my_custom_post_type' );
function create_my_custom_post_type(){
$labels = array( ... );
$args = array( ... );
register_post_type( 'my_custom_post_type', $args );
}
现在,因为我试图以正确的方式进行操作,所以我没有这样做,而是转到 /includes
目录中的文件 class-plugin-name.php
并创建了一个新的私有函数,如下所示:
class Plugin_Name {
private function register_my_custom_post_type(){
$labels = array( ... );
$args = array( ... );
register_post_type( 'my_custom_post_type', $args );
}
public function __construct(){
// This was also added to my constructor
$this->register_my_custom_post_type();
}
}
因为这是 运行 每次调用插件时,我认为 post 类型会完美创建,但我收到此错误:
Fatal error: Call to a member function add_rewrite_tag() on a
non-object in /public_html/wordpress/wp-includes/rewrite.php on line
51
我很确定问题出在我的新功能上,有人知道如何正确执行吗?也许我应该把代码放在 class 之外,然后创建一个新的 class 并为 init?
创建一个钩子
您关于连接到 init
以注册自定义 post 类型的做法是正确的。这是正确的语法:
public function __construct() {
add_action( 'init', array( $this, 'register_my_custom_post_type' ) );
}
我需要为插件创建自定义 post 类型。好吧,我决定以面向对象的方式创建插件,所以基本上我使用 Devin Vinson 的 WordPress-Plugin-Boilerplate 作为起点。
我见过许多插件在主插件文件中添加自定义 post 类型,如下所示:
add_action( 'init', 'create_my_custom_post_type' );
function create_my_custom_post_type(){
$labels = array( ... );
$args = array( ... );
register_post_type( 'my_custom_post_type', $args );
}
现在,因为我试图以正确的方式进行操作,所以我没有这样做,而是转到 /includes
目录中的文件 class-plugin-name.php
并创建了一个新的私有函数,如下所示:
class Plugin_Name {
private function register_my_custom_post_type(){
$labels = array( ... );
$args = array( ... );
register_post_type( 'my_custom_post_type', $args );
}
public function __construct(){
// This was also added to my constructor
$this->register_my_custom_post_type();
}
}
因为这是 运行 每次调用插件时,我认为 post 类型会完美创建,但我收到此错误:
Fatal error: Call to a member function add_rewrite_tag() on a non-object in /public_html/wordpress/wp-includes/rewrite.php on line 51
我很确定问题出在我的新功能上,有人知道如何正确执行吗?也许我应该把代码放在 class 之外,然后创建一个新的 class 并为 init?
创建一个钩子您关于连接到 init
以注册自定义 post 类型的做法是正确的。这是正确的语法:
public function __construct() {
add_action( 'init', array( $this, 'register_my_custom_post_type' ) );
}