最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to get category name or ID by post?

programmeradmin0浏览0评论

I'm trying to display category name inside a foreach post ..

<?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(); ?>

Does not work !

I'm trying to display category name inside a foreach post ..

<?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(); ?>

Does not work !

Share Improve this question asked May 4, 2019 at 11:55 warzonemasterwarzonemaster 51 silver badge3 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Please try below updated code

<?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(); ?>

Try and let me know if any query.

Hope it will help!

发布评论

评论列表(0)

  1. 暂无评论