Skip to content

Instantly share code, notes, and snippets.

@billerickson
Created November 15, 2018 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save billerickson/06ee7c4737f529f4d3b71a00aae1c133 to your computer and use it in GitHub Desktop.
Save billerickson/06ee7c4737f529f4d3b71a00aae1c133 to your computer and use it in GitHub Desktop.
<?php
/**
* Related Posts by category
*
* @author Bill Erickson
* @see https://www.billerickson.net/custom-wordpress-queries/
*/
function be_related_posts_by_category() {
$categories = get_the_terms( get_the_ID(), 'category' );
$category = array_shift( $categories );
$loop = new WP_Query( array(
'posts_per_page' => 5,
'category_name' => $category->slug,
'post__not_in' => array( get_the_ID() )
) );
if( $loop->have_posts() ):
echo '<div class="related-posts">';
echo '<h3>Related Posts</h3>';
while( $loop->have_posts() ): $loop->the_post();
echo '<div class="related-post">';
if( has_post_thumbnail() )
echo '<a class="entry-image-link" href="' . get_permalink() . '">' . get_the_post_thumbnail( get_the_ID(), 'medium' ) . '</a>';
echo '<h5 class="entry-title"><a href="' . get_permalink() . '">' . get_the_title() . '</a></h5>';
echo '</div>';
endwhile;
echo '</div>';
endif;
wp_reset_postdata();
}
add_action( 'genesis_after_entry', 'be_related_posts_by_category' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment