显示帖子类别但返回空数组

问题描述

每当我尝试获取帖子的类别名称时,它都会返回一个空的“数组”。我不精通 wordpress 中的 PHP,但我已经尝试了很多方法来让它工作。我曾尝试同时使用 get_the_category()the_category(','),但后者提取类别名称并将它们完全放在函数的开头(看起来它完全从它们中剥离了 div)。>

我想显示每个帖子所属的类别列表,并将它们保留在我的 div ID 中。奇怪的是(对我而言),get_the_date() 原样工作得很好,但 get_the_category() 没有。

橙色的“Array”应该显示以逗号分隔的类别名称(理想情况下):

"Array" in orange should be showing category names separated by commas (ideally)

这是我用来在我的functions.PHP文件获取帖子的代码

function ctmblog_posts() { 
 
// Query Arguments
$ctmblog_args = array(
'orderby' => 'date','ignore_sticky_posts' => '1','cat' => 8,88,87,5 // Use the category id,can also replace with category_name which uses category slug
    //'category_name' => array(SLUG OF FOO CATEGORY),);

//Loop to display 10 recently updated posts
$ctmblog_loop = new WP_Query( $ctmblog_args );
$counter = 1;
$string .= '<ul><div id="timeline">';
while( $ctmblog_loop->have_posts() && $counter < 10 ) : $ctmblog_loop->the_post();
$string .= '<div id="timeline_event"><span id="timeline_date">'. get_the_date() .'</span> — '.'<span id="timeline_category">' .get_the_category() . '</span>'.' <br><li><a href="' . get_permalink( $ctmblog_loop->post->ID ) . '"> ' .get_the_title( $ctmblog_loop->post->ID ) . '</a></li></div>';
$counter++;
endwhile; 
$string .= '</div></ul>';
return $string;
wp_reset_postdata(); 
} 
 
//add a shortcode
add_shortcode('blog-posts','ctmblog_posts');

如果我能得到任何指点,我将不胜感激!这对我来说是一次很棒的学习经历。我在网上搜索并尝试了其他人向其他人建议的解决方案,但我认为这对我来说可能是一个独特的案例。

解决方法

让我们阅读 get_the_category() 函数的文档:https://developer.wordpress.org/reference/functions/get_the_category/

应该可以吧?让我们记住,在 WordPress 中,每篇文章都可以有多个类别 - 这会导致函数返回一个数组。

代码来自 wordpress.org 用户 Stefano

$categories = get_the_terms( $post->ID,'taxonomy' );
// now you can view your category in array:
// using var_dump( $categories );
// or you can take all with foreach:
foreach( $categories as $category ) {
    echo $category->term_id . ',' . $category->slug . ',' . $category->name . '<br />';
}