Khi bài viết được xuất bản, WordPress sẽ tự động thay thế shortcode này bằng danh sách các bài viết liên quan theo cùng một danh mục với bài viết hiện tại. Thêm mã sau vào functions.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 52 53 54 55 56 57 58 |
// Code tạo shortcode bài viết liên quan cho Webdy function webdy_related_post($content) { if(is_singular('post')) { global $post; ob_start(); $categories = get_the_category($post->ID); if ($categories) { $category_ids = array(); foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id; $args=array( 'category__in' => $category_ids, 'post__not_in' => array($post->ID), 'posts_per_page'=>6, 'ignore_sticky_posts'=>1 ); $my_query = new wp_query( $args ); if( $my_query->have_posts() ) {?> <div class="relatedcat"> <div class="row related-post"> <?php while ($my_query->have_posts()):$my_query->the_post(); ?> <div class="col large-4"> <a href="<?php echo get_the_permalink(); ?>" title="<?php echo get_the_title(); ?>"> <div class="feature"> <div class="image" style="background-image:url(<?php echo get_the_post_thumbnail_url();?>);"></div> </div> </a> <div class="related-title post-title"> <a href="<?php echo get_the_permalink(); ?>" title="<?php echo get_the_title(); ?>"><?php echo get_the_title(); ?></a> </div> <div class='cat-label'> <?php $post = get_post(); $cats = array(); foreach (get_the_category($post_id) as $c) { $cat = get_category($c); array_push($cats, $cat->name); } if (sizeOf($cats) > 0) { $post_categories = implode(', ', $cats); } echo $post_categories; ?> </div> </div> <?php endwhile; ?> </div> </div> <?php } // end if has post } // end if $categories $related_post = ob_get_contents(); ob_end_clean(); return $content.$related_post; } //end if is single post else return $content; } add_shortcode('webdy_related_post', 'webdy_related_post'); |
Trong trình soạn thảo bài viết, nơi bạn muốn hiển thị bài viết liên quan, chỉ cần…