Skip to content

Instantly share code, notes, and snippets.

@billerickson
Last active December 27, 2015 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save billerickson/7271816 to your computer and use it in GitHub Desktop.
Save billerickson/7271816 to your computer and use it in GitHub Desktop.
<?php
/**
* Related Posts
*
*/
function be_related_posts() {
$categories = get_the_category( get_the_ID() );
$args = array(
'posts_per_page' => 4,
'post__not_in' => array( get_the_ID() ),
'category_name' => $categories[0]->slug
);
$loop = new WP_Query( $args );
if( $loop->have_posts() ):
echo '<div class="related-posts"><h3>Related Posts</h3>';
while( $loop->have_posts() ): $loop->the_post();
$classes = 'one-half';
if( 0 == $loop->current_post || 0 == $loop->current_post % 2 )
$classes .= ' first';
echo '<div class="' . $classes . '"><a href="' . get_permalink() . '">' . get_the_post_thumbnail( get_the_ID(), 'thumbnail' ) . '</a></div>';
endwhile;
echo '</div>';
endif;
wp_reset_postdata();
}
add_action( 'genesis_after_entry', 'be_related_posts' );
@thoughtwell
Copy link

Bill, in the $args variable, what does the 'post__not_in' do? Also, can you explain what $categories[0]->slug is doing?

I can see how you use some wordpress functions like 'get_the_category' to pull posts from categories. I'm guessing get_the_ID is probably pulling the current page ID and correlating that to the post's category to effect the outcome of the related posts?

I've looked at using get_taxonomy and a few of the other taxonomic functions, but I'm just not real sure what to put in for my parameters. It seems like these functions have you declare either an ID, slug, or category-name... but what if you aren't sure what category will be displaying since the template is the same for 100 different custom custom post types that may fall under one of 10 taxonomic identifiers? Would use use something similar to get_the_ID as a parameter to pull the items you want into your related items feed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment