简体   繁体   English

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

[英]Get archive category ID of custom post type

I'm trying to get the ID of the category on a category archive page of a custom post type. 我正在尝试在自定义帖子类型的类别存档页面上获取该类别的ID。 So far, I'm using the code below, but it doesn't seem to be working. 到目前为止,我正在使用下面的代码,但它似乎没有工作。 This code is in my taxonomy-{taxonomy}.php file. 此代码位于我的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

Do I need to do something special for retrieving the ID of a category of a custom post type? 我是否需要做一些特殊的事情来检索自定义帖子类型的ID?

As a side note, I need this, so I can pass the ID into the get_categories() function 作为旁注,我需要这个,所以我可以将ID传递给get_categories()函数

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

$categories = get_categories($args);

There are several ways to get the category id 有几种方法可以获得类别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'); }

OR just 要不就

var_dump($wp_query->get_queried_object())

will give the current object for the template like for query on a category archive this is the category object 将给出模板的当前对象,就像对类别存档的查询一样,这是类别对象

OR even none of these worked then here is the custom query 或者甚至这些都没有在这里工作是自定义查询

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

wp_get_ post _categories can only get POST categories not a custom post's categories, try this instead: wp_get_ post _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 http://wordpress.org/support/topic/wp_get_post_categories-equivalent-for-custom-taxonomies

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM