以编程方式插入类别

时间:2015-10-25 作者:stlawrance

我想知道我应该如何以编程方式插入类别,并且应该在主题激活后只插入一次。

我知道这里。

function example_insert_category() {
    wp_insert_term(
        \'Science\',
        \'category\',
        array(
          \'description\' => \'This is an Science category.\',
          \'slug\'        => \'science\'
        )
    );
}
add_action( \'after_setup_theme\', \'example_insert_category\' );
我不知道如何插入子项等。我想插入如下结构的类别:

Science
--Grade 11
----Science
----Management
----Humanities
--Grade 12
----Science
----Management
----Humanities

MIT
--Grade 15
----Science
----Management
----Humanities
--Grade 16
----Science
----Management
----Humanities
是否可以通过编程实现?

谢谢

1 个回复
最合适的回答,由SO网友:chrisguitarguy 整理而成

跟踪return value of wp_insert_term 并用它来构建你的结构。成功的返回值将是具有term_id 可以传递到的密钥wp_insert_term\'s$args 数组作为parent.

$parent = wp_insert_term(\'Science\', \'category\'); // I\'ll leave out `$args` here
if (is_wp_error($parent)) {
  // insert didn\'t work! return from your function or error or whatever
  return;
}

// grade 11 category has "Sience" as its parent
$grade11 = wp_insert_term(\'Grade 11\', \'category\', [\'parent\' => $parent[\'term_id\']]);
if (is_wp_error($grade11)) {
  // same as above, something went wrong
  return;
}

// Management has the parent "Grade 11"
wp_insert_term(\'Management\', \'category\', [\'parent\' => $grade11[\'term_id\']]);
只要插入一次,就可以钩住after_switch_theme 做你的事。您可能希望首先查找您的术语,以确保它没有被插入,或者在成功时使用插入的术语ID设置一个选项。

add_action(\'after_switch_theme\', \'wpse206511_switch\');
function wpse206511_switch()
{
    if (get_option(\'wpse206511_term_id\')) {
        // already done, bail
        return;
    }

    // category insert code from above

    // set the term ID in an option that you can check later
    // if/when the theme gets activated/deactivated again
    add_option(\'wpse206511_term_id\', $parent[\'term_id\']);
}

相关推荐

显示所有类别而不是分配给特定帖子的类别的GET_TERMS

我的自定义帖子类型中有3篇帖子(\'careers\'). 我注册了自定义分类法(\'career_categories\').我创建了3个职位,其中两个职位属于“全职”,一个职位属于“兼职”。我在循环中使用以下代码:$terms = get_terms( \'career_categories\', array( \'hide_empty\' => true, ) ); $html_out .= \'<td class=\"column-\'. $col++ .\'\"&g