問題描述

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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。