• Resolved mrspabs

    (@mrspabs)


    I am using this code to show other posts from the same category on single.php

    <?php
    global $post;
    $cat_ID=array();
    $categories = get_the_category(); //get all categories for this post
      foreach($categories as $category) {
        array_push($cat_ID,$category->cat_ID);
      }
      $args = array(
      'orderby' => 'date',
      'order' => 'DESC',
    	'post_type' => 'post',
    	'numberposts' => 8,
    	'post__not_in' => array($post->ID),
    	'category__in' => $cat_ID
      ); // post__not_in will exclude the post we are displaying
        $cat_posts = get_posts($args);
    if ($cat_posts) {
      foreach ($cat_posts as $cat_post) {
        ?>
        <div class="col-md-3 text-center">   
    
     <a href="<?php echo get_permalink($cat_post->ID); ?>">Link</a></div><!--// col-md-3 -->
    <?php $counter++; if ($counter % 4 == 0) { echo '</div><div class="row">'; } ?>
        <?php
      }
    }
    ?>

    How can i modify this code so that instead of Link, it shows the featured image and the post title?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter mrspabs

    (@mrspabs)

    Thanks! That helped a lot. I was able to write it like this and it works.

    <?php
    global $post;
    $cat_ID=array();
    $categories = get_the_category(); //get all categories for this post
      foreach($categories as $category) {
        array_push($cat_ID,$category->cat_ID);
      }
      $args = array(
      'orderby' => 'date',
      'order' => 'DESC',
    	'post_type' => 'post',
    	'numberposts' => 8,
    	'post__not_in' => array($post->ID),
    	'category__in' => $cat_ID
      ); // post__not_in will exclude the post we are displaying
        $cat_posts = get_posts($args);
    if ($cat_posts) {
      foreach ($cat_posts as $cat_post) {
        ?>
        <div class="col-md-3 text-center">
     <a href="<?php echo get_permalink($cat_post->ID); ?>">  <?php echo get_the_post_thumbnail( $cat_post->ID, 'medium' ); ?><br>
     <?php echo get_the_title($cat_post->ID); ?></a>
     </div><!--// col-md-3 -->
    <?php $counter++; if ($counter % 4 == 0) { echo '</div><div class="row">'; } ?>
        <?php
      }
    }
    ?>

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Get the title and featured image via post id’ is closed to new replies.