forked from dalenguyen/wordpress-snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshow_related_posts_on_single.php
51 lines (35 loc) · 1.11 KB
/
show_related_posts_on_single.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
// Show related posts @ single post
function related_posts() {
// current post id
$current_post_id = get_the_ID();
$related = new WP_Query(
array(
'category__in' => wp_get_post_categories( $current_post_id ),
'posts_per_page' => 4,
'orderby' => 'rand',
'post__not_in' => array( $current_post_id ) // exlcude currnet post
)
);
if( $related->have_posts() ) {
echo '<div class="all-related-posts">';
while( $related->have_posts() ) { $related->the_post();
// related post data
$post_id = get_the_ID();
$post_title = get_the_title( $post_id );
$post_permalink = get_the_permalink( $post_id );
$post_featured_image = get_the_post_thumbnail( $post_id, 'medium' );
// entry div structure
echo '<div class="related-post-item">';
echo '<div class="post-featured-image">'. $post_featured_image .'</div>';
echo '<h3 class="post-title">'. $post_title .'</h3>';
echo '<a href="'. $post_permalink .'" class="button">Read More</a>';
echo '</div>';
}
echo '</div>';
}
else {
echo '<p>No related post found!!!</p>';
}
wp_reset_postdata();
}