在WordPress自定义分类法中创建术语



我创建了一个自定义的帖子类型Properties,在其中我创建了名为Position的自定义分类法,在其中,我想创建一些术语。我使用下面的代码创建了术语Slider,效果很好。

function realestatepro_custom_terms() {
    wp_insert_term(
      'Slider', // the term 
      'Position', // the taxonomy
          array(
            'description'=> 'Will be featured in the home page slider.',
            'slug' => 'home-page-slider'
          )
    );

}
add_action( 'init', 'realestatepro_custom_terms' );

但我想创建更多的术语,比如"特色"one_answers"推广",但我不确定如何创建,我确实考虑过重复整个wp_insert_terms块,但这似乎不对,然后我试图在第一个之后直接添加另一个术语,但这不起作用。

有人知道添加多个术语的最佳方法吗?

wp_insert_term()是一个大函数,包含许多清理、操作和错误检查。没有一个版本会重复。因此,您必须将wp_insert_term()封装到foreach循环中。

function realestatepro_custom_terms() {
    $terms = array(
      'Slider' => array(
        'description'=> 'Will be featured in the home page slider.',
        'slug' => 'home-page-slider'
      ),
      'Featured' => array( /*properties*/ 
      ),
      'Promoted' => array( /*properties*/ 
      )
    );
    foreach($terms as $term => $meta){
        wp_insert_term(
          $term, // the term 
          'Position', // the taxonomy
          $meta
        );
    }
}
add_action( 'init', 'realestatepro_custom_terms' );

另一种可能性是你可以像这样使用wp_set_object_terms()

$terms = array( 'Featured', 'Promoted', 'Slider');
wp_set_object_terms( $object_id, $terms, 'Position' );

其中$object_id是您创建的伪Properties post。添加条款后,您可以删除帖子。这里的问题是,你不能像slug或description那样设置任何术语meta。此外,wp_set_object_terms()函数简单地包含foreach循环,其中类似于第一解重复wp_insert_term()。没什么太壮观的。我真的不推荐第二种选择,只是出于兴趣。

最新更新