Skip to content

Instantly share code, notes, and snippets.

@FerFuego
Last active August 12, 2020 13:04
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 FerFuego/628fef2145d740451194d106e107787d to your computer and use it in GitHub Desktop.
Save FerFuego/628fef2145d740451194d106e107787d to your computer and use it in GitHub Desktop.
Related Post Category
<?php
/**
* Return html
*/
function related_post() {
$post_id = get_the_ID();
$post_type = get_post_type($post_id);
$cat_ids = array();
$categories = get_the_category( $post_id );
if(!empty($categories) && is_wp_error($categories)):
foreach ($categories as $category):
array_push($cat_ids, $category->term_id);
endforeach;
endif;
$args = array(
'post_type' => $post_type,
'category__in' => $cat_ids,
'post__not_in' => array($post_id),
'posts_per_page' => '6'
);
$query = new WP_Query( $args );
if($query->have_posts()): ?>
<ul>
<?php while($query->have_posts()): $query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
<?php the_content(); ?>
</li>
<?php endwhile; ?>
</ul>
wp_reset_postdata();
endif;
}
?>
<?php echo related_post(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment