php – Display related posts without a plugin

Question

I’m trying to display the related posts using functions.php:

function posts_related($related){ if (is_single()) {
global $post;
// Build basic custom query arguments
$custom_query = new WP_Query( array( 
       'posts_per_page' => 8, // Number of related posts to display
       'post__not_in' => array($post->ID), // Ensure that the current post is not displayed
       'orderby' => 'rand', // Randomize the results
));

// Run the loop and output data for the results
if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); 
 if ( has_post_thumbnail()
  ) { 
                 $permalink = the_permalink();
                 $post_thumbnail = the_post_thumbnail('medium');
                 $title = the_title();                       
                 $related .= '<a href="' . $permalink .  '"><img src="' . $post_thumbnail . '/></a>';             
                 }
           $related .=  '<a href="' .  $permalink . '"><b>' . $title . '</b></a>';
     endwhile; 
 else : 
    $related .= '<p>Nothing to show.</p>';
endif;
// Reset postdata
}
         echo '<pre>'; var_dump( has_post_thumbnail() ); echo '</pre>'; 

    return $related;

}    //wp_reset_postdata();

add_filter( "the_content", "posts_related", 99 );
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 100, 50, true );

But I’m not being able to handle the output properly. I need it to display below the post (single post).

0
023023 2 years 2021-05-02T19:06:52-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse