問題描述
WordPress 預設分類 (Categories) 預設情況下未分類。如何新增預設專案到新的自定義分類?
的 functions.php:
// === CUSTOM TAXONOMIES === //
function my_custom_taxonomies() {
register_taxonomy(
'block', // internal name = machine-readable taxonomy name
'static_content', // object type = post, page, link, or custom post-type
array(
'hierarchical' => true,
'labels' => array(
'name' => __( 'Blocks' ),
'singular_name' => __( 'Block' ),
'add_new_item' => 'Add New Block',
'edit_item' => 'Edit Block',
'new_item' => 'New Block',
'search_items' => 'Search Block',
'not_found' => 'No Block found',
'not_found_in_trash' => 'No Block found in trash',
),
'query_var' => true, // enable taxonomy-specific querying
'rewrite' => array( 'slug' => 'block' ), // pretty permalinks for your taxonomy?
)
);
}
add_action('init', 'my_custom_taxonomies', 0);
編輯:安裝主題時,我只希望有分類專案。它不必自動新增到任何空白的術語。
最佳解決方案
看看這裡:
http://wordpress.mfields.org/2010/set-default-terms-for-your-custom-taxonomies-in-wordpress-3-0/
基本上,您需要做的是使用 save_post 鉤子來檢查帖子的條款,如果它是空的,則從您的分類學中新增預設術語。
如果您只想在自定義分類法中設定初始項,那麼可以使用 wp_insert_term()。可能最簡單的方法是將其新增到您用來建立自定義分類法的相同功能中。由於 t3ios 在註釋中新增,您應該首先呼叫 get_term(),如果返回值為空,則只插入該術語 (即術語不存在) 。
此示例程式碼來自 Codex:http://codex.wordpress.org/Function_Reference/wp_insert_term
$parent_term = term_exists( 'fruits', 'product' ); // array is returned if taxonomy is given
$parent_term_id = $parent_term['term_id']; // get numeric term id
wp_insert_term(
'Apple', // the term
'product', // the taxonomy
array(
'description'=> 'A yummy apple.'
'slug' => 'apple'
'parent'=> $parent_term_id
)
);
次佳解決方案
預設類別是 wp_insert_post()功能的硬編碼情況。
所以它不能完全複製,但你可以用其他方式來處理它。我會嘗試鉤入 post status transition 的新帖子,並分配想要的預設術語,如果沒有在建立後分配。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。