Skip to main content

[Thủ Thuật WordPress] Tạo một Custom Post Type trong WordPress

Custom post type là gì

WordPress sẽ cho bạn Page và Post để xuất bản nội dung và hai cái này được gọi là post type.

Nếu bạn có nhu cầu sử dụng nhiều hơn 2 post type, ví dụ làm thêm một post type khác với mục đích đăng quản lý profile, sản phẩm ... thì bắt buộc chúng ta phải tự tạo một post type khác, và cái post type mà do chúng ta tự tạo ra thì được gọi là Custom Post Type.

Tạo một Custom Post Type trong WordPress

Đây là snippet code tạo mẫu một custom post type "Animals", bạn có thể đặt nó vào file functions.php của theme.


function wptp_create_post_type() {
    $labels = array( 
		'name' => __( 'Animals' ),
		'singular_name' => __( 'animal' ),
		'add_new' => __( 'New animal' ),
		'add_new_item' => __( 'Add New animal' ),
		'edit_item' => __( 'Edit animal' ),
		'new_item' => __( 'New animal' ),
		'view_item' => __( 'View animal' ),
		'search_items' => __( 'Search animals' ),
		'not_found' =>  __( 'No animals Found' ),
		'not_found_in_trash' => __( 'No animals found in Trash' ),
	);
	$args = array(
		'labels' => $labels,
		'has_archive' => true,
		'public' => true,
		'hierarchical' => false,
		'supports' => array(
			'title', 
			'editor', 
			'excerpt', 
			'custom-fields', 
			'thumbnail',
			'page-attributes'
		),
		'taxonomies' => array( 'post_tag', 'category'), 
	);
	register_post_type( 'animal', $args );
} 
add_action( 'init', 'wptp_create_post_type' );

Cách hiển thị Custom Post Type 

Để hiển thị post type bạn cần sử dụng query 

$args = array(
    'post_type' => 'animal',
    'post_status' => 'publish',
   'posts_per_page' => -1,
);
$query = new WP_Query( $args );
<?php if( $query ->have_posts() ): ?>
     <?php while( $query ->have_posts() ) : $query ->the_post(); ?>
      // Thông tin cần lấy của 1 bài viết
      <?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); ?>

Các Plugin có thể tạo Custom Post Type nhanh chóng

Ngoài cách code bạn có thể dùng các plugin hỗ trợ nhanh chóng, bạn hãy tham khảo các plugin bên dưới

  1. Custom Post Type UI
  2. WCK Custom Post Types and Custom Fields Creator
  3. Pods
  4. Toolset Types
  5.  Custom Post Type Maker