我试图在foreach帖子中显示类别名称。。
<?php
$recent_posts = wp_get_recent_posts(array(
\'post_status\' => \'publish\',
\'cat\' => \'\',
));
foreach($recent_posts as $post) : ?>
<div class="card">
<div class="card-bg">
<div class="card-cat">
<?php foreach((get_the_category()) as $category) {
echo $category->name.\'\';
} ?>
</div>
<img class="card-img" src="<?php echo get_the_post_thumbnail_url( $post[\'ID\'] ); ?>">
</div>
<div class="card-body">
<div class="card-title">
<?php echo $post[\'post_title\'] ?>
</div>
</div>
</div>
<?php endforeach;
wp_reset_query(); ?>
不起作用!
最合适的回答,由SO网友:Pratik Patel 整理而成
请尝试以下更新的代码
<?php
$recent_posts = wp_get_recent_posts(array(
\'post_status\' => \'publish\',
\'cat\' => \'\',
));
foreach($recent_posts as $post) : ?>
<div class="card">
<div class="card-bg">
<div class="card-cat">
<?php
$category_detail=get_the_category($post[\'ID\']);//Pass POST ID
foreach($category_detail as $cd){
echo $cd->cat_name.\'\';
}
?>
</div>
<img class="card-img" src="<?php echo get_the_post_thumbnail_url( $post[\'ID\'] ); ?>">
</div>
<div class="card-body">
<div class="card-title">
<?php echo $post[\'post_title\'] ?>
</div>
</div>
</div>
<?php endforeach;
wp_reset_query(); ?>
如果有任何疑问,请告诉我。
希望这会有帮助!