10

如何在archive.php 页面上“获取”自定义类别名称或ID。因此,当我在该页面模板上时,我如何知道正在显示哪些自定义类别帖子?

4

5 回答 5

37

用于get_queried_object();检索当前查询的对象。

在分类术语案例中:

//Custom taxonomy is project_type, custom term is web-design
$obj = get_queried_object();

echo '<pre>';
print_r( $obj );
echo '</pre>';

显示以下内容:

stdClass Object
(
    [term_id] => 56
    [name] => Web Design
    [slug] => web-design
    [term_group] => 0
    [term_taxonomy_id] => 56
    [taxonomy] => project_type
    [description] => Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    [parent] => 0
    [count] => 0
)

希望能帮助到你!

于 2013-08-26T14:07:46.007 回答
6

检查此代码是否有帮助?

if ( is_single() ) {
$cats =  get_the_category();
$cat = $cats[0]; // let's just assume the post has one category
}
else { // category archives
$cat = get_category( get_query_var( 'cat' ) );
}
$cat_id = $cat->cat_ID;
$cat_name = $cat->name;
$cat_slug = $cat->slug;
于 2013-08-26T09:15:54.080 回答
2

如果您尝试在您的 archive.php 页面上显示当前类别,例如,如果您的 url 是:

www.sitename.com/category/design

然后回显“设计”,您将使用以下内容:

single_cat_title();

在我的存档页面上,我有以下内容:

<h1 class="page-heading"><?php single_cat_title(); ?></h1>

这会在 h1 标记中显示类别“设计”。我希望这可以帮助别人。

于 2013-12-28T09:34:01.160 回答
1

简单的就是最好的

$term_id       =    get_queried_object_id();
$prod_term        =    get_term($term_id,'product_cat');
$current_cat_slug =    $prod_term->slug;    
于 2018-10-17T07:38:33.487 回答
0

试试这段代码来获取类别名称!!$cat_name = single_cat_title('',false);

于 2013-08-26T14:36:06.160 回答