[英]WordPress get_terms() function not display custom taxonomy categories for woocommerce
[英]WordPress: Why Can't get_terms() See Custom Taxonomy Registered inside Class?
我在類中注冊了自定義帖子類型和自定義分類法。 在WP管理員內部,我既看到了職位類型,又看到了分類法。
class Custom_Post_Type {
function __construct($init_data) {
if ( is_admin() ) {
add_action( 'init', array( $this, 'create_ctp' ) );
add_action( 'admin_head', array( $this, 'create_ctp_icons' ) );
add_action( 'save_post', array( $this, 'save_ctp_custom_metadata' ), 1, 2 );
}
}
function create_ctp_taxonomy() {
register_taxonomy(
$post_type.'_type',
$post_type,
array(
'labels' => array(
'name' => $taxonomy_label,
'add_new_item' => 'Add New '.$taxonomy_label
),
'public' => true,
'show_ui' => true,
'show_tagcloud' => true,
'hierarchical' => true,
'show_in_nav_menus' => true,
'show_admin_column' => true
)
);
register_post_type($post_type_slug,
array(
'labels' => array(),
'public' => true,
'has_archive' => false,
'supports' => $this->supports,
'register_meta_box_cb' => array( $this, 'create_ctp_custom_metaboxes' ),
'taxonomies' => array( $taxonomy_slug ),
)
);
}
}
同樣,這在管理區域內有效。 我可以添加帖子,也可以看到分類法並添加條款。
在前端, get_taxonomies()
沒有看到新的自定義分類法,而get_terms()
沒有看到其中的術語。
我嘗試了register_taxonomy
幾個示例,當我在類之外使用它時,它出現在前端。 但是,當我將示例移到內部create_ctp_taxonomy函數中時,它們對於get_taxonomies
突然不可見。
任何想法為什么會這樣?
我一直在玩各種不同的事情,我認為這里的問題是init
動作的時機。 當我從__construct
函數調用安裝函數方向時,而不是添加操作,事情就開始起作用了。 例:
class Custom_Post_Type {
function __construct($init_data) {
if ( is_admin() ) {
//add_action( 'init', array( $this, 'create_ctp' ) );
add_action( 'admin_head', array( $this, 'create_ctp_icons' ) );
add_action( 'save_post', array( $this, 'save_ctp_custom_metadata' ), 1, 2 );
}
$this->create_cpt();
}
}
通過這樣做,我完全跳過了使用init
的過程。 但是,這似乎違反了標准做法。 任何人都知道這樣做有不利之處嗎?
將分類法注冊到自定義帖子類型時,需要注意幾件事。
register_post_type
函數的taxonomies參數將分類法注冊為帖子類型。 例如。
register_post_type('cpt_name',array(
'taxonomies'=>array(
'taxomony_name1',
'taxomony_name2')
,other_arguments...)
);
來自文檔
注冊帖子類型時,請始終使用taxonomies參數注冊您的分類法。 如果不這樣做,則在使用諸如parse_query或pre_get_posts之類的過濾器時,分類法和帖子類型將不會被識別為已連接。 這可能會導致意外結果和故障
1.)問題不是比賽條件。
直接從functions.php
運行時,諸如is_admin()
類的條件仍然有效。 這與網絡上的某些信息相矛盾,但是從WordPress 4.4開始,這些信息確實起作用。
2.)從add_action()
而不是直接從__construct()
調用注冊
直接切換到調用注冊的更改為零。 需要明確的是,兩者之間沒有區別:
$this->create_ctp()
add_action('init', array( $this, 'create_ctp' ) );
3.)分類法與CTP的注冊順序
當我將分類法注冊移到CTP之前時,其行為更改為零。
我正在使用is_admin()
的條件檢查,這是我在添加admin破折號時先前添加的要包裝的內容。 這就是為什么我的CTP出現在后端而不是前端的原因。
我已經從簡化的示例中刪除了它,因此無法通過查看我發布的代碼來分辨。
因此,我要做的就是刪除is_admin()
檢查。 事實證明這是一個愚蠢的錯誤,但對於查找實際上不是問題的信息很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.