简体   繁体   English

WordPress获取每个类别上的类别名称

[英]Wordpress get the category name on each category

I want to make the code to display 'MORE STORIES FROM #CATEGORYNAME' as a title of the box that appears. 我想让代码显示“来自#CATEGORYNAME的更多故事”作为出现的框的标题。 As the user is viewing different category the name to change. 当用户查看其他类别时,名称将更改。

Ex. 例如 User is viewing a post in category 'cars' when the box appears the title would be MORE STORIES FROM 'cars'. 当框出现时,用户正在查看类别“汽车”中的帖子,标题将是“汽车”中的更多故事。

When he switch to category 'IT', the name to be 'MORE STORIES FROM IT' 当他切换到“ IT”类别时,其名称为“来自IT的更多故事”

if(!emptry($td_query_more_article->posts)) {?>
    <div class="td-more-articles-box">
     <i class=td-icon-close td-close-more-articles-box"></i>
     <span class="td-more-articles-box-title"><?php echo __td('MORE STORIES', TD_THEME_NAME) ?></span>
    <div class="td-content-more-articles-box">

I hope I was specific enough. 我希望我足够具体。 Corrent me if I am wrong 如果我做错了,请允许我

Sorry, this needs bit more clarification how you want to achieve this; 抱歉,这需要您进一步说明如何实现。 do you want this on widget or add it statically on the theme? 您要在小部件上使用此控件还是将其静态添加到主题上? Is there a reason why excisting plugins don't work for you? 为什么现有的插件无法为您服务?

If you are in the WordPress loop, you can simply using the following: 如果您处于WordPress循环中,则可以使用以下命令:

$categories = get_the_category();

if ( ! empty( $categories ) ) {
    echo esc_html( $categories[0]->name );   
}

This will give you the first category if there are more than one. 如果有多个类别,这将为您提供第一类。

If you are not in the loop, you will need to pass the post id as a parameter, like this; 如果您不在循环中,则需要将post id作为参数传递;

// get the post object
global $post; 

// pass post id
$categories = get_the_category($post->ID); 

if ( ! empty( $categories ) ) {
    echo esc_html( $categories[0]->name );   
}

You can get category name using this function. 您可以使用此功能获取类别名称。

$cat_name = get_category(get_query_var('cat'))->name; $ cat_name = get_category(get_query_var('cat'))->名称;

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

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