如何为自定义分类定义术语

时间:2012-06-10 作者:Shimon S

我有一个自定义的帖子类型,叫做q-questions, 它有一个自定义的分类法q-categories.
我通过插入帖子wp_insert_post 我想为分类法定义一些术语,我的代码是:

$my_post = array(
\'post_title\' => \'Custom-tax\',
\'post_content\' => \'This is my post.\',
\'post_type\' => \'q-questions\',
 );

$post_id = wp_insert_post( $my_post );
我应该如何定义q-categories 对于此帖子为my-category?

3 个回复
SO网友:Tyler Carter

类别只是一种分类法。分类法是由术语组成的。您需要通过wp_set_post_terms.

这应该相当简单:

wp_set_post_terms( \'42\', array( \'term\', \'terms\', \'terms\' ), \'q-categories\' );

SO网友:Stephen Harris

Codex:

$post = array(
   ...
  \'tax_input\' => [ array( \'taxonomy_name\' => array( \'term\', \'term2\', \'term3\' ) ) ]  
   ...
);  
因此,以您为例:

$my_post = array(
  \'post_title\' => \'Custom-tax\',
  \'post_content\' => \'This is my post.\',
  \'post_type\' => \'q-questions\',
  \'tax_input\'=>array(
     \'q-categories\' => array(\'my-category\'),
   )
 );

$post_id = wp_insert_post( $my_post );

SO网友:mitesh

您必须注册自定义纹理。在函数中添加以下代码。php。Ref

//hook into the init action and call create_question_taxonomies when it fires
add_action( \'init\', \'create_question_taxonomies\', 0 );

//create two taxonomies, genres and writers for the post type "question"
function create_question_taxonomies() 
{
  // Add new taxonomy, make it hierarchical (like categories)
  $labels = array(
    \'name\' => _x( \'q-categories\', \'taxonomy general name\' ),
    \'singular_name\' => _x( \'q-category\', \'taxonomy singular name\' ),
    \'search_items\' =>  __( \'Search q-categories\' ),
    \'all_items\' => __( \'All q-categories\' ),
    \'parent_item\' => __( \'Parent q-categories\' ),
    \'parent_item_colon\' => __( \'Parent q-categories:\' ),
    \'edit_item\' => __( \'Edit q-categories\' ), 
    \'update_item\' => __( \'Update q-categories\' ),
    \'add_new_item\' => __( \'Add New q-categories\' ),
    \'new_item_name\' => __( \'New q-categories Name\' ),
    \'menu_name\' => __( \'q-categories\' ),
  );     

  register_taxonomy(\'q-categories\',array(\'question\'), array(
    \'hierarchical\' => true,
    \'labels\' => $labels,
    \'show_ui\' => true,
    \'show_admin_column\' => true,
    \'query_var\' => true,
    \'rewrite\' => array( \'slug\' => \'q-categories\' ),
  ));

}
然后您只需在wp\\u insert\\u post之后添加以下代码

wp_set_post_terms( $post_id, array( \'term\', \'terms\', \'terms\' ), \'q-categories\' );

结束

相关推荐

Sort Archive by Taxonomy

我有一个网站,上面有各州的分类法(如维多利亚州、肯斯兰州等)。这种分类法被称为listing\\u State。我还有一个名为membership\\u type的分类法,它可以是免费的,也可以是付费的。这两种税收经济适用于上市公司的CPT如果我点击一个州的分类法,它会按照预期结果按发布日期排序,我会如何在免费会员之前列出付费会员。我正在使用Genesis和Lifestyle主题谢斯里查德