自定义帖子类型的get_categories

时间:2012-07-26 21:18:11

标签: wordpress custom-post-type

我有自定义帖子类型,'ioni_codex' 我使用内置的Wordpress类别作为分类法

我想列出'ioni_codex'使用的所有类别。

我认为这段代码可以解决问题:

$myargs = array (
    'type' => 'ioni_codex'
); 
$categories = get_categories( $myargs );

但是我看到所有类别的列表不是'ioni_codex'指定的类别。

我做错了什么?

2 个答案:

答案 0 :(得分:3)

get_categories()不接受post_type作为参数,而是使用taxonomy,并在注册时通过您给出的名称来引用分类。这是一个代码的链接,可以更详细地解释它 - http://codex.wordpress.org/Function_Reference/get_categories

答案 1 :(得分:0)

我在姐妹项目上得到答案: Bainternet♦重写了get_terms()函数以提供post_type

请参阅他的解决方案here或仅从下方复制和过去:

/* get terms limited to post type 
 @ $taxonomies - (string|array) (required) The taxonomies to retrieve terms from. 
 @ $args  -  (string|array) all Possible Arguments of get_terms http://codex.wordpress.org/Function_Reference/get_terms
 @ $post_type - (string|array) of post types to limit the terms to
 @ $fields - (string) What to return (default all) accepts ID,name,all,get_terms. 
 if you want to use get_terms arguments then $fields must be set to 'get_terms'
*/
function get_terms_by_post_type($taxonomies,$args,$post_type,$fields = 'all'){
    $args = array(
        'post_type' => (array)$post_type,
        'posts_per_page' => -1
    );
    $the_query = new WP_Query( $args );
    $terms = array();
    while ($the_query->have_posts()){
        $the_query->the_post();
        $curent_terms = wp_get_object_terms( $post->ID, $taxonomy);
        foreach ($curent_terms as $t){
          //avoid duplicates
            if (!in_array($t,$terms)){
                $terms[] = $c;
            }
        }
    }
    wp_reset_query();
    //return array of term objects
    if ($fields == "all")
        return $terms;
    //return array of term ID's
    if ($fields == "ID"){
        foreach ($terms as $t){
            $re[] = $t->term_id;
        }
        return $re;
    }
    //return array of term names
    if ($fields == "name"){
        foreach ($terms as $t){
            $re[] = $t->name;
        }
        return $re;
    }
    // get terms with get_terms arguments
    if ($fields == "get_terms"){
        $terms2 = get_terms( $taxonomies, $args );
        foreach ($terms as $t){
            if (in_array($t,$terms2)){
                $re[] = $t;
            }
        }
        return $re;
    }
}