Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ibrahimkholil/0ea8edff16a01195c8bdb4d17a6b1f5d to your computer and use it in GitHub Desktop.
Save ibrahimkholil/0ea8edff16a01195c8bdb4d17a6b1f5d to your computer and use it in GitHub Desktop.
How to automatically insert a list of related articles below the post
/*********************************************************************************/
/*How to automatically insert a list of related articles below the post*/
/*********************************************************************************/
function wptuts_more_from_cat( $title = "More From This Category:" ) {
global $post;
// We should get the first category of the post
$categories = get_the_category( $post->ID );
$first_cat = $categories[0]->cat_ID;
// Let's start the $output by displaying the title and opening the <ul>
$output = '<div id="more-from-cat"><h4>' . $title . '</h4><hr>';
// The arguments of the post list!
$args = array(
// It should be in the first category of our post:
'category__in' => array( $first_cat ),
// Our post should NOT be in the list:
'post__not_in' => array( $post->ID ),
// ...And it should fetch 5 posts - you can change this number if you like:
'posts_per_page' => 3,
'orderby' => 'rand',
);
// The get_posts() function
$posts = get_posts( $args );
if( $posts ) {
$output .= '<ul>';
// Let's start the loop!
foreach( $posts as $post ) {
setup_postdata( $post );
$post_thumb = get_the_post_thumbnail();
$post_title = get_the_title();
$permalink = get_permalink();
$output .= '<li class="col-lg-4 col-md-4 col-sm-4 col-xs-12"><a href="' . $permalink . '" title="' . esc_attr( $post_title ) . '">' . $post_thumb . '</a><a href="' . $permalink . '" class="more-from-cat" title="' . esc_attr( $post_title ) . '">' . $post_title . '</a></li>';
}
$output .= '</ul><div class="clearfix"></div>';
} else {
// If there are no posts, we should return something, too!
$output .= '<p>Sorry, this category has just one post and you just read it!</p>';
}
// Let's close the <div> and return the $output:
$output .= '</div>';
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment