3

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

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

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

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

但是,相反,我看到的是所有类别的列表,而不是“ioni_codex”分配的类别。

我究竟做错了什么?

4

3 回答 3

6

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

于 2012-07-26T21:35:41.407 回答
0

我在一个姊妹项目中有一个答案:Bainternet♦ 已经重写了 get_terms() 函数来提供 post_type

请在此处参考他的解决方案,或者从下面复制并过去:

/* 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;
    }
}
于 2012-07-27T14:15:53.723 回答
0

您必须设置 post_type 而不是 type ,默认情况下 get_categories 尝试隐藏空类别,如果您想显示它全部添加 hide_empty 属性设置为 false

 get_categories(array(
    'post_type' => 'ioni_codex',
    'hide_empty' => false,
   ) );

于 2021-09-24T04:51:10.950 回答