Code Samples /

Related Posts

The code below will display a list of related content based on the selected categories of the current post.

single.php
<?php 
get_header(); 

the_title('<h1>', '</h1>'); 
the_content(); 

// Get Related Posts .
$terms = get_the_category($post->ID); // get current categories.
$term_array = []; // Create empty category array.
   
foreach( $terms as $term ) { // Loop found categories.
   $term_array[] = $term->slug;
}
   
// Render Ajax Load More shortcode
echo do_shortcode( '[ajax_load_more category="'. implode( ",", $term_array ) .'" post__not_in="'. $post->ID .'"]' );

get_footer();
PHP

Note: This can also be used for tags and custom taxonomies by replacing get_the_categories() with the appropriate function.


« Back to Code Samples