|
1 | 1 | <?php |
2 | 2 |
|
3 | | -// Show related posts @ single post |
| 3 | +// Show related posts @ single post. |
4 | 4 |
|
| 5 | +/** |
| 6 | + * Show random posts from the same categories as the current post. |
| 7 | + * |
| 8 | + * @return void |
| 9 | + */ |
5 | 10 | function related_posts() { |
6 | 11 |
|
7 | | - // current post id |
| 12 | + // current post id. |
8 | 13 | $current_post_id = get_the_ID(); |
9 | 14 |
|
10 | 15 | $related = new WP_Query( |
11 | 16 | array( |
12 | 17 | 'category__in' => wp_get_post_categories( $current_post_id ), |
13 | 18 | 'posts_per_page' => 4, |
14 | 19 | 'orderby' => 'rand', |
15 | | - 'post__not_in' => array( $current_post_id ) // exlcude currnet post |
| 20 | + 'post__not_in' => array( $current_post_id ), // exclude current post. |
16 | 21 | ) |
17 | 22 | ); |
18 | 23 |
|
19 | 24 | if ( $related->have_posts() ) { |
20 | 25 |
|
21 | 26 | echo '<div class="all-related-posts">'; |
22 | 27 |
|
23 | | - while ( $related->have_posts() ) { $related->the_post(); |
| 28 | + while ( $related->have_posts() ) { |
| 29 | + $related->the_post(); |
24 | 30 |
|
25 | | - // related post data |
26 | | - $post_id = get_the_ID(); |
27 | | - $post_title = get_the_title( $post_id ); |
28 | | - $post_permalink = get_the_permalink( $post_id ); |
29 | | - $post_featured_image = get_the_post_thumbnail( $post_id, 'medium' ); |
| 31 | + // entry div structure. |
| 32 | + echo '<div class="related-post-item">'; |
| 33 | + echo '<div class="post-featured-image">'; |
| 34 | + the_post_thumbnail( 'medium' ); |
| 35 | + echo '</div>'; |
| 36 | + echo '<h3 class="post-title">' . esc_html( get_the_title() ) . '</h3>'; |
| 37 | + echo '<a href="' . esc_url( get_the_permalink() ) . '" class="button">Read More</a>'; |
| 38 | + echo '</div>'; |
30 | 39 |
|
31 | | - // entry div structure |
32 | | - echo '<div class="related-post-item">'; |
33 | | - echo '<div class="post-featured-image">' . $post_featured_image . '</div>'; |
34 | | - echo '<h3 class="post-title">' . $post_title . '</h3>'; |
35 | | - echo '<a href="' . $post_permalink . '" class="button">Read More</a>'; |
36 | | - echo '</div>'; |
37 | | - |
38 | | - } |
| 40 | + } |
39 | 41 |
|
40 | 42 | echo '</div>'; |
41 | 43 |
|
|
0 commit comments