Bước 1:
Đầu tiên, bạn cần sao chép mã mẫu sau và dán nó vào file functions.php của chủ đề WordPress của bạn. Bạn có thể truy cập nó qua Appearance > Theme Editor và chọn functions.php.
// Code bài viết liên quan cho chủ đề Flatsome function flatsome_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"> <p class="related-post-title">Bài viết liên quan:</p> <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"><a href="<?php echo get_the_permalink(); ?>" title="<?php echo get_the_title(); ?>"><?php echo get_the_title(); ?></a></div> </div> <?php endwhile; ?> </div> </div> <style> .relatedcat { padding-top: 10px; border-top: 1px solid #e8e8e8; margin-top: 20px; } p.related-post-title { font-size: 18px; font-weight: bold; } .feature { position: relative; overflow: hidden; } .feature::before { content: ""; display: block; padding-top: 56.25%; } .feature .image { position: absolute; top: 0; left: 0; bottom: 0; right: 0; margin: auto; background-size: cover; background-position: center; } ul.row.related-post li { list-style: none; } .related-title { line-height: 1.3 !important; margin-top: 10px !important; } </style> <?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_filter('the_content', 'flatsome_related_post');
Bước 2:
Sau khi bạn đã dán mã mẫu vào functions.php, hãy lưu thay đổi.
Bước 3:
Bây giờ, khi bạn viết hoặc chỉnh sửa một bài viết, các bài viết liên quan sẽ tự động xuất hiện ở cuối bài viết.
Lưu ý rằng bạn có thể tùy chỉnh giao diện và CSS cho phần bài viết liên quan bằng cách sửa đổi phần CSS trong mã mẫu.
comments