-
-
Save billerickson/06ee7c4737f529f4d3b71a00aae1c133 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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