获取自定义帖子类型的归档类别ID

时间:2013-07-10 20:22:57

标签: php wordpress

我正在尝试在自定义帖子类型的类别存档页面上获取该类别的ID。到目前为止,我正在使用下面的代码,但它似乎没有工作。此代码位于我的taxonomy-{taxonomy}.php文件中。

$cat_name = single_cat_title('', false);
$cat_id = get_cat_ID($cat_name);

// $cat_name = 'Category Name', which works fine but,
// $cat_id = 0, which is obviously not the id of the category

我是否需要做一些特别的事情来检索自定义帖子类型的类别的ID?

作为旁注,我需要这个,所以我可以将ID传递给get_categories()函数

$args = array(
    'child_of' => $cat_id,
    'taxonomy' => 'taxonomy'
);

$categories = get_categories($args);

2 个答案:

答案 0 :(得分:3)

有几种方法可以获得类别ID

$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;

OR

$category = get_the_category(); 
$cat_id = $category[0]->cat_ID; // or foreach through

OR

if(is_category()) { $cat_ID = get_query_var('cat'); }

或者只是

var_dump($wp_query->get_queried_object())

将为模板提供当前对象,例如查询类别存档,这是类别对象

或者甚至这些都不起作用,这里是自定义查询

global $wpdb;
$category=$wpdb->get_results("SELECT * FROM `wp_terms` WHERE `name` ='$cat_name'");
$category[0]->term_id;

答案 1 :(得分:1)

wp_get_ 帖子 _categories只能获取POST类别而非自定义帖子的类别,请尝试以下方式:

$category = get_the_terms( $post->ID, 'custom-taxonomy-here' ); //////find custom taxonomy category name
foreach ( $category as $cat){
echo $cat->name;
}

http://wordpress.org/support/topic/wp_get_post_categories-equivalent-for-custom-taxonomies