Nếu bạn nào không muốn dùng plugin có sẵn trên mạng thì mình xin chia sẻ đoạn code làm điều này , các bạn chỉ cần past đoạn code này vào file single.php trong folder giao diện của các bạn :
Trong bài viết này mình có 2 lựa chọn dành cho bạn:
Lựa chọn thứ nhất : Hiển thị bài viết liên quan dựa trên các thẻ tag của bài viết .
03 | $tags = wp_get_post_tags( $post ->ID); |
08 | foreach ( $tags as $each_tag ) |
09 | $tag_ids [] = $each_tag ->term_id; |
14 | 'post__not_in' => array ( $post ->ID), |
18 | 'ignore_sticky_posts' => 1 |
20 | $query = new WP_Query( $args ); |
22 | if ( $query ->have_posts() ) { |
24 | echo '<h3>Related Article(s):</h3><ol>' ; |
26 | while ( $query ->have_posts()) { |
29 | <li><a href= "<?php the_permalink() ?>" rel= "bookmark" title= "Permanent Link to: <?php the_title_attribute(); ?>" > |
30 | <?php the_title(); ?></a></li> |
Lựa chọn thứ hai : Hiển thị bài viết liên quan dựa trên danh mục của bài viết (category).
03 | $category_ids = array (); |
05 | foreach ( $categories as $each_category ) |
06 | $category_ids [] = $each_category ->term_id; |
10 | 'post__not_in' => array ( $post ->ID), |
14 | 'ignore_sticky_posts' => 1 |
16 | $query = new WP_Query( $args ); |
18 | if ( $query ->have_posts() ) { |
20 | echo '<h3>Related Article(s):</h3><ol>' ; |
21 | while ( $query ->have_posts()) { |
24 | <li><a href= "<?php the_permalink() ?>" rel= "bookmark" title= "Permanent Link to: <?php the_title_attribute(); ?>" > |
25 | <?php the_title(); ?></a></li> |
Sau khi bạn quyết định lựa chọn của mình, thì copy và past code tương ứng vào file single.php. File này nằm trong folder theme mà bạn đang sử dụng. Đoạn code phải được đặt bên dưới hàm the_content()như đoạn code minh họa bên dưới :
02 | <!-- part of the single.php code removed for brevity. --> |
03 | <?php if (have_posts()) : while (have_posts()) : the_post(); ?> |
05 | <div <?php post_class() ?> id= "post-<?php the_ID(); ?>" > |
07 | <span><?php the_time( 'd' ) ?></span><br /> |
08 | <span><?php the_time( 'M' ) ?></span><br /> |
09 | <span><?php the_time( 'Y' ) ?></span> |
14 | <h2><a href= "<?php the_permalink() ?>" rel= "bookmark" title= "Permanent Link to <?php the_title_attribute(); ?>" ><?php the_title(); ?></a></h2> |
16 | <?php the_content( 'Read the rest of this entry »' ); ?> |
17 | <?php wp_link_pages( array ( 'before' => '<p><span>Pages:</span> ' , 'after' => '</p>' , 'next_or_number' => 'number' )); ?> |
20 | <!-- Đây là nơi bạn sẽ đặt đoạn code mà bạn muốn hiển thị |
22 | <!-- Kết thúc đoạn code ở đây --> |
27 | <?php comments_template(); ?> |
29 | <?php endwhile ; else : ?> |
30 | <p id= "rightcolumn" >Sorry, no posts matched your criteria.</p> |
33 | <?php get_sidebar(); ?> |
Nếu bạn cảm thấy việc code tay như vậy sẽ làm bạn cảm thấy mất thời gian hay khó thực hiện thì có thể tham khảo bài viết Top 5 plugin tạo tin liên quan cho trang WordPress
Chúc các bạn thành công !
Comments[ 0 ]
Đăng nhận xét