|
$related = get_posts( |
|
array( |
|
'category__in' => wp_get_post_categories( $post->ID ), |
|
'numberposts' => 5, |
|
'post__not_in' => array( $post->ID ) |
|
) |
|
); |
|
|
|
if( $related ) { |
|
foreach( $related as $post ) { |
|
setup_postdata($post); |
|
/*whatever you want to output*/ |
|
} |
|
wp_reset_postdata(); |
|
} |
|
|
|
//////////////////////// |
|
Reference: |
|
- get_posts |
|
- wp_reset_postdata |
|
- wp_get_post_categories |
|
//////////////////////// |
|
|
|
Answer re-written based on WP_Query(): |
|
|
|
$related = new WP_Query( |
|
array( |
|
'category__in' => wp_get_post_categories( $post->ID ), |
|
'posts_per_page' => 5, |
|
'post__not_in' => array( $post->ID ) |
|
) |
|
); |
|
|
|
if( $related->have_posts() ) { |
|
while( $related->have_posts() ) { |
|
$related->the_post(); |
|
/*whatever you want to output*/ |
|
} |
|
wp_reset_postdata(); |
|
} |
|
|
|
|
|
|
|
// for functions.php |
|
|
|
function example_cats_related_post() { |
|
|
|
$post_id = get_the_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; |
|
|
|
$current_post_type = get_post_type($post_id); |
|
$query_args = array( |
|
|
|
'category__in' => $cat_ids, |
|
'post_type' => $current_post_type, |
|
'post_not_in' => array($post_id), |
|
'posts_per_page' => '3' |
|
|
|
|
|
); |
|
|
|
$related_cats_post = new WP_Query( $query_args ); |
|
|
|
if($related_cats_post->have_posts()): |
|
while($related_cats_post->have_posts()): $related_cats_post->the_post(); ?> |
|
<ul> |
|
<li> |
|
<a href="<?php the_permalink(); ?>"> |
|
<?php the_title(); ?> |
|
</a> |
|
<?php the_content(); ?> |
|
</li> |
|
</ul> |
|
<?php endwhile; |
|
|
|
// Restore original Post Data |
|
wp_reset_postdata(); |
|
endif; |
|
|
|
} |
|
|
|
Now you can simply call the function anywhere in your site using: |
|
php example_cats_related_post() |
|
|
|
reference: https://wordpress.stackexchange.com/questions/30039/how-to-display-related-posts-from-same-category |
|
|
|
|