Code hiển thị bài viết theo chuyên mục trong WordPress

5/5 - (1 bình chọn)

Dưới đây là cách hiển thị bài viết theo chuyên mục (Recent Post WordPress) trong WordPress, với đoạn code này chúng ta có thể hoàn toàn tùy biến chúng.

Bài viết dành cho các bạn đang làm nghề thiết kế WordPress, WordPress Delelopment, thiết kế theme WordPress.
Bước 1: Tạo 1 file có tên loop-web5c1.php trong thư mục theme WordPress với nội dung sau:

<?php for ($i = 1; $i <= 1; $i++) {?>
<a href='<?php the_permalink(); ?>' title='<?php the_title();?>'>
<?php the_post_thumbnail('skip_post_thumb'); ?>
<h1><?php the_title();?></h1>
<p><?php the_excerpt(); ?></p>
</a>
<?php }?>
Ghi chú: 
– Hiển thị ảnh đại diện thumbnail: <?php the_post_thumbnail(‘skip_post_thumb’); ?>
– Hiển thị Tiêu đề bài viết: <?php the_title();?>
– Hiển thị đoạn mô tả dưới tiêu đề bài viết: <?php the_excerpt(); ?>
– Hiển thị liên kết bài viết: <?php the_permalink(); ?>
  • Bước 2: Chèn đoạn code sau vào nơi cần hiển thị bài viết, Recent post
 <?php query_posts('showposts=1&category_name=khach-hang-doi-tac&orderby=DESC');
if (have_posts()):
while (have_posts()):

the_post(); {get_template_part('loop', 'web5c1');}
endwhile;
wp_reset_query();
endif;
?>
Ghi chú:
– Hiển thị số bài viết: showposts=1
– Hiển thị bài viết thuộc category: category_name=khach-hang-doi-tac

** Nếu muốn hiển thị bài viết cho toàn trang web WordPress, hãy chỉnh sửa nó trở thành như sau:

<?php query_posts('showposts=1&orderby=DESC');
if (have_posts()):
while (have_posts()):

the_post(); {get_template_part('loop', 'web5c1');}
endwhile;
wp_reset_query();
endif;

?>
để hiển thị những bài viết tiếp theo trong 1 chuyên mục.

Ví dụ: đoạn code ở bước 2, bạn đã hiển thị được 1 bài. Giờ đây, bạn muốn hiển thị thêm 2 bài liên tiếp (trừ bài đầu tiên) thì dùng đoạn code sau đây:

<?php query_posts('offset=1&showposts=2&category_name=khach-hang-doi-tac&orderby=DESC');
if (have_posts()):
while (have_posts()):
the_post(); {get_template_part('loop', 'web5c1');}
endwhile;
wp_reset_query();
endif;
?>
5/5 - (1 bình chọn)


Trả lời