Hướng dẫn tạo bài viết cùng chủ đề, chuyên mục, ngẫu nhiên wordpress

Admin

AdminAdmin is verified member.

Well-Known Member
Staff member
Administrator
Chào các bạn, ở bài này mình sẽ giới thiệu cách để hiển thị các bài viết theo các tiêu chí sau:
- Hiển thị bài viết liên quan theo tags.
- Hiển thị bài viết cùng chuyên mục.
- Hiển thị bài viết ngẫu nhiên.
Hiển thị bài viết liên quan theo tags
Bạn copy hàm sau vào file functions.php.

// Show related post by tagsfunction get_related_post_tags(){$tags = wp_get_post_tags($post->ID);if ($tags){$tag_ids = array();foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id; $args=array('tag__in' => $tag_ids,'post__not_in' => array($post->ID),'showposts'=>5, // Number of post you want to show'caller_get_posts'=>1);$my_query = new wp_query($args);if( $my_query->have_posts() ){echo '<ul>';while ($my_query->have_posts()){$my_query->the_post();?><li><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li><?php}echo '</ul>';}}}
Tại chỗ muốn hiển thị, ví dụ như ở trang index. Bạn dùng code sau:


<?php get_related_post_tags();?>
Hiển thị bài viết theo chuyên mục (Category)
Tương tự như trên, bạn sẽ tạo hàm sau.

// Show related post by categoryfunction get_related_post_category(){$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),'showposts'=>5, // Number of post you want to show'caller_get_posts'=>1);$my_query = new wp_query($args);if( $my_query->have_posts() ){echo '<ul>';while ($my_query->have_posts()){$my_query->the_post();?><li><a href="<?php the_permalink() ?>" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li><?php}echo '</ul>';}}}
Copy vào chỗ muốn hiển thị đoạn code sau:

<?php get_related_post_category();?>
Bài viết ngẫu nhiên

//Show random postfunction get_random_post(){_e("<ul>");$randPosts = new WP_Query();$randPosts->query('showposts=5&orderby=rand');while($randPosts->have_posts()) : $randPosts->the_post();_e("<li>");?><a href="<?php the_permalink();?>"><?php the_title();?></a><?php_e("</li>");endwhile;_e("</ul>");}


<?php get_random_post();?>
Xong
 

Facebook Comments

Similar threads

Admin
Replies
0
Views
1K
AdminAdmin is verified member.
Admin
Admin
Replies
0
Views
1K
AdminAdmin is verified member.
Admin
Admin
Replies
1
Views
950
blog4meblog4me is verified member.
blog4me
Admin
Replies
0
Views
1K
AdminAdmin is verified member.
Admin
blog4me
Replies
0
Views
1K
blog4meblog4me is verified member.
blog4me
Admin
Replies
0
Views
969
AdminAdmin is verified member.
Admin
Admin
Replies
0
Views
2K
AdminAdmin is verified member.
Admin
Admin
Replies
0
Views
529
AdminAdmin is verified member.
Admin
S
Replies
0
Views
681
shirauno
S
Back
Top