如何通过帖子类型获取所有条款

时间:2015-11-22 13:42:13

标签: wordpress

我需要在自定义帖子类型

中的自定义分类中获取所有

这是我的尝试:

function gat_all_terms($taxonomy){

$terms = get_terms( $taxonomy, 'orderby=count&hide_empty=0' );
$count = count($terms);
$out ='';
if ( $count > 0 ){
 foreach ( $terms as $term ) {
   $out .= "<li class='item'> <a href='#'>" . $term->name . "</a></li>";

 }
}
return $out;
}

但我无法检测到自定义帖子类型。

1 个答案:

答案 0 :(得分:3)

如果您尝试获取自定义帖子类型的条款,可以在此处查看答案:

https://wordpress.stackexchange.com/questions/14331/get-terms-by-taxonomy-and-post-type

static public function get_terms_by_post_type( $taxonomies, $post_types ) {

    global $wpdb;

    $query = $wpdb->prepare(
        "SELECT t.*, COUNT(*) from $wpdb->terms AS t
        INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
        INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id
        INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id
        WHERE p.post_type IN('%s') AND tt.taxonomy IN('%s')
        GROUP BY t.term_id",
        join( "', '", $post_types ),
        join( "', '", $taxonomies )
    );

    $results = $wpdb->get_results( $query );

    return $results;

}

您可以将其转换为更简单的内容:

function get_terms_by_post_type( $taxonomy, $post_type ) {

    global $wpdb;

    $query = $wpdb->prepare(
        "SELECT t.*, COUNT(*) from $wpdb->terms AS t
        INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
        INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id
        INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id
        WHERE p.post_type IN('%s') AND tt.taxonomy IN('%s')
        GROUP BY t.term_id",
        $post_type,
        $taxonomy
    );

    $results = $wpdb->get_results( $query );

    return $results;

}

get_terms_by_post_type( 'taxonomy', 'type' );