[英]How to add a custom post type in my OOP plugin?
我需要為插件創建自定義帖子類型。 好吧,我決定以OOP方式創建插件,因此基本上我使用了Devin Vinson的WordPress-Plugin-Boilerplate作為起點。
我見過很多插件,它們在主插件文件中添加了自定義帖子類型,如下所示:
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();
}
}
由於每次調用插件時都會運行此程序,因此我認為可以完美創建帖子類型,但出現此錯誤:
致命錯誤:在第51行的/public_html/wordpress/wp-includes/rewrite.php中的非對象上調用成員函數add_rewrite_tag()
我很確定問題出在我的新功能上,有人對如何正確執行操作有任何想法嗎? 也許我應該將代碼放在該類之外,而只需創建一個新類並為init創建一個鈎子?
您對掛鈎init
注冊您的自定義帖子類型是正確的。 這是正確的語法:
public function __construct() {
add_action( 'init', array( $this, 'register_my_custom_post_type' ) );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.