Site icon Init HTML

Tạo và sử dụng Custom Post Types

Thêm Taxonomy

Ví dụ thêm một Taxonomy là Series cho Post để gom các bài viết vào một Series (như Init HTML đang có).

/*
 * Register SERIES tax
 */
function create_series_tax() {
	register_taxonomy(
		'series',
		'post',
		array(
			'label' => __('Series'),
			'rewrite' => array('slug' => 'series'),
			'hierarchical' => true,
		)
	);
}
add_action('init', 'create_series_tax');

Kết quả:

Sử dụng Taxonomy

Theo ví dụ trên, để sử dụng, các bạn tạo thêm file taxonomy-series.php, với mã nguồn giống như category.php là được.

global $query_string;
query_posts($query_string);
if (have_posts()) : while (have_posts()) : the_post();
// Danh sách bài viết trong Series
endwhile; endif;

Thêm Post Types

Ví dụ thêm Định nghĩa (như Init HTML đang có).

/**
 * Register GLOSSARY post type
 */
function create_glossary_post_type() {
      register_post_type('glossary',
            array(
                  'labels' => array(
                  'name' => __('Định Nghĩa'),
                  'menu_name' => __('Định nghĩa'),
                  'singular_name' => __('Định nghĩa'),
                  'all_items' => __('Tất cả định nghĩa'),
                  'add_new' => __('Viết bài mới'),
                  'add_new_item' => __('Thêm định nghĩa mới'),
                  'edit' => __('Sửa định nghĩa'),
                  'edit_item' => __('Sửa định nghĩa'),
                  'new_item' => __('Định nghĩa mới'),
                  'view' => __('Xem định nghĩa'),
                  'view_item' => __('Xem định nghĩa'),
                  'search_items' => __('Tìm định nghĩa'),
                  'not_found' => __('Không tìm thấy định nghĩa'),
                  'not_found_in_trash' => __('Không tìm thấy định nghĩa')
            ),
            'public' => true,
            'show_ui' => true,
            'capability_type' => 'post',
            'publicy_queryable' => true,
            'exclude_from_search' => false,
            'menu_position' => 4,
            'hierarchical' => false,
            'show_in_nav_menus' => true,
            'has_archive' => true,
            'query_var' => true,
            'supports' => array(
                        'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments'
                  ),
            'rewrite' => array('slug' => 'dinh-nghia', 'with_front' => false),
            'can_export' => true,
            'description' => __('glossary')
      ));
}
add_action('init', 'create_glossary_post_type');

Kết quả:

Bạn có thể dùng đoạn mã tạo Taxonomy ở trên để tạo Category cho Post Types này. Lưu ý thay post bằng glossary.

Sử dụng

Để đầy đủ, chúng ta cần 2 tập tin mới trong theme: archive-glossary.php để liệt kê danh sách bài viết và single-glossary.php để xem bài viết.

Để lấy bài viết là Định nghĩa, ta sử dụng:

query_posts('post_type=glossary');

Chúc các bạn thành công!

Exit mobile version