Làm Archive template trên Gatsby

Ngày đăng: 02 - 06 - 2020 Lượt xem: 567 lượt

Trong bài trước mình cùng mọi người làm  sidebar cho page template trên Gatsby. Thì với bài viết này chúng ta cùng tìm hiểu cách thực tạo archive template từ WordPress sang Gatsby.

Archive template trên Gatsby

Trước tiên các bạn vào folder templates tạo file archive.js và sau đó khởi tạo component template.


import React from 'react'
const Archive = () =>{  return()}
export default Archive;

Sau đó các bạn tạo custom post type trong WordPress. Mình sẽ lấy ví dụ là tạo Blog trong WordPress với đoạn code như sau:


function theme_products(){
    $label = array(
        'name' => 'Blogs',
        'singular_name' => 'Blogs' ,
		'add_new'               => __( 'Thêm blog', 'textdomain' ),
        'add_new_item'          => __( 'Tên blog', 'textdomain' ),
        'new_item'              => __( 'Blog mới', 'textdomain' ),
        'edit_item'             => __( 'Chỉnh sửa blog', 'textdomain' ),
        'view_item'             => __( 'Xem blog', 'textdomain' ),
        'all_items'             => __( 'Tất cả blog', 'textdomain' ),
        'search_items'          => __( 'Tìm kiếm blog', 'textdomain' ),
	'featured_image'        => _x( 'Hình ảnh blog', 'textdomain' ),
        'set_featured_image'    => _x( 'Chọn hình ảnh blog', 'textdomain' ),
        'remove_featured_image' => _x( 'Xóa hình ảnh blog', 'textdomain' ),
    );
    $args = array(
        'labels' => $label,
        'description' => 'Phần blog theme',
        'supports' => array(
            'title',
            'editor',
            'thumbnail',
            'custom-fields'
        ),
        'hierarchical' => false,
        'order' => 'DESC',
        'orderby' => 'date',
        'posts_per_page' => 30,
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'show_in_nav_menus' => true,
        'show_in_admin_bar' => true,
        'show_in_rest' => true,
        'rest_base'          => 'blogs',
        'menu_position' => 5,
        'menu_icon'           => 'dashicons-book-alt',
        'can_export' => true,
        'has_archive' => true,
        'publicly_queryable' => true,
        'capability_type' => 'post'
    );
    register_post_type('theme_products', $args);
}
add_action('init', 'theme_products');

Điều đặt biết ở đây là mình thêm vào dòng

'show_in_rest' => true

Dòng này giúp đưa custom post type vừa tạo vào api mặc định của WordPress các bạn kiểm ta bằng cách  bật GraphQL trong Gatsby

gatsby develop

Sau đó các bạn query như sau:

 {allWordpressWpBlogs(sort: {fields: date, order: DESC}) {
                   edges {
                     node {
                       id
                       title
                       slug
                       content
                       date(formatString: "DD,MMMM, YYYY")
                       featured_media {
                         source_url
                       }
                     }
                   }
                 }
               }

Sau khi thêm dòn show-in-rest trên GraphQL hiện các thành phần liên quan đến custom post type blog  trong đoạn query trên mình có thêm thuộc tính sắp xếp giảm dần theo thời gian. Tức là bài blog nào đăng gần nhất sẽ được xếp ở đầu. Tiếp theo mình thêm thuôc tính date formate cho trường thông tin date của Blog. Có rất nhiều kiểu date format trong GraphQL các bạn có thể tham khảo thêm tại đây. Bước tiếp theo chúng ta sẽ vào file gatsby-node.js để truyền các bài Blog vào archive.js:


.then(()=>{
      graphql(`
                {
                 allWordpressWpBlogs(sort: {fields: date, order: DESC}) {
                   edges {
                     node {
                       id
                       title
                       slug
                       content
                       date(formatString: "DD,MMMM, YYYY")
                       featured_media {
                         source_url
                       }
                     }
                   }
                 }
               }
      `).then(result =>{
          if (result.errors) {
            console.log(result.errors);
            reject(result.errors);
          }
          const webPageTemplate = path.resolve('./src/templates/archive.js');
          Array.from({length: numberOfPages}).forEach((page, index) => {
            _.each(result.data.allWordpressWpBlogs.edges, edge => {
            createPage({
              path: `/${edge.node.slug}`,
              component: slash(webPageTemplate),
              context: edge.node
            });
          });
      });
    })

Các bạn thêm đoạn này  nối đuôi  phần .then() của phần tạo page trong bài trước. Vậy là chúng ta bước đầu đã xong việc còn lại là các bạn vào lại archive.js truyền pageContext và render giao diện theo ý muốn.

Tổng kết

Vậy là mình đã hướng dẫn xong các bạn tạo trang archive cho custom post type Blog. Qua bài kế tiếp mình sẽ hướng dẫn các bạn các chèn thêm pagination.

Cảm ơn các bạn đã theo dõi

5 1 vote
Đánh giá bài viết

Nhận thông báo
Nhận thông báo cho
guest

0 Góp ý
Inline Feedbacks
View all comments

Bài viết liên quan

Thêm pagination và sidebar vào archive template trên Gatsby

Thêm pagination và sidebar vào archive template trên Gatsby

05 - 06 - 2020

Trong bài trước mình cùng mọi người cách tạo archive template trên Gatsby. Bài viết lần này mình và các...

Thêm sidebar vào page template trên Gatsby

Thêm sidebar vào page template trên Gatsby

27 - 05 - 2020

Trong bài trước mình cùng mọi người làm  page template trong Gatsby. Thì hôm nay mình tiếp tục hướng...

Làm Page template trên Gatbsy

Làm Page template trên Gatbsy

25 - 05 - 2020

Trong bài trước mình cùng mọi người luyện tập sử dụng custom field từ WordPress để render phần tin...

Render Tin tức mới của homepage trên Gatsby

Render Tin tức mới của homepage trên Gatsby

18 - 05 - 2020

Trong bài trước mình cùng mọi người luyện tập sử dụng custom field từ WordPress để render sang giao...

Render slider và CTA images của homepage trên Gatsby

Render slider và CTA images của homepage trên Gatsby

17 - 05 - 2020

Trong bài trước mình đã hướng dẫn các bạn render footer từ WordPress sang Gatsby. Nói đơn giản là các...

Render footer từ WordPress sang Gatsby

Render footer từ WordPress sang Gatsby

11 - 05 - 2020

Trong bài trước mình đã hướng dẫn các bạn làm overlay menu trên Gatsby. Thì với bài lần này...

0
Would love your thoughts, please comment.x