Skip to content

Instantly share code, notes, and snippets.

Created November 19, 2017 06:51
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 anonymous/c5e2b2efa5f495c4d8b35fb4fde534da to your computer and use it in GitHub Desktop.
Save anonymous/c5e2b2efa5f495c4d8b35fb4fde534da to your computer and use it in GitHub Desktop.
function profitmag_related_post( $post_id ) {
$categories = get_the_category( $post_id );
if( $categories ) {
$category_ids = array();
foreach( $categories as $category ) {
$category_ids[] = $category->term_id;
}
$args = array(
'category__in' => $category_ids,
'post__not_in' => array( $post_id ),
'posts_per_page' => 4,
);
$related_query = new WP_Query( $args );
if( $related_query->have_posts() ) {
echo '<ul>';
while( $related_query->have_posts()){
$related_query->the_post();
?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
}
echo '</ul>';
?>
<?php
}else {
?>
<ul><li><?php _e( 'No related post.', 'profitmag'); ?></li></ul>
<?php
}
wp_reset_postdata();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment