hướng dẫn tạo Custom Post Type

 

Trong WordPress, có hai loại posttype chính có sẵn để hiển thị nội dung của các website cơ bản đó là  Post và Page . Tuy nhiên theo từng yêu cầu của khách hàng/ website, lĩnh vực mà Post và Page không đáp ứng được các chức năng đưa ra. Custom Post Type là giải pháp cho chúng ta đối với những lĩnh vực này.

Tạo custom post type bằng với code

Mẫu code:

function tao_custom_post_type() {
    $args = array(); 
    register_post_type( 'slug-post-type' , $args );
}
add_action( 'init', 'tao_custom_post_type' );

hàm cốt lõi để tạo custom post type là register_post_type( ‘slug-post-type’ , $args ). trong đó slug-post-type là slug của post type muốn tạo, $args là mảng tham số truyền vào thông tin post type mới. tuy nhiên tôi sẽ không trình bày toàn bộ. các bạn nếu muốn tìm hiểu kỹ hơn hãy tham khảo tại đây 

Ví dụ tôi muốn tạo một custom post type cho dự án tôi có đoạn code như sau:

function create_project_post_type() {

    $label = array(
        'name' => _('Projects'), 
        'singular_name' => _('Project') ,
		'all_items'     => 'All Projects',
		'add_new' => 'Add new', 
		'add_new_item' => 'Add new Project', 
		'edit_item' => 'Edit Project', 
		'new_item' => 'Add new Project' 
    );


    $supports = array(
        'title', 
        'editor', 
        'excerpt', 
        'author', 
        'thumbnail', 
    );

    $args = array(
        'labels' => $label,
        'description' => 'Post type post project',
        'supports' => $supports,
        'taxonomies' => array( 'category' ),
        'hierarchical' => false, 
        'public' => true, 
        'show_ui' => true, 
        'show_in_menu' => true, 
        'show_in_nav_menus' => true, 
        'show_in_admin_bar' => true, 
        'menu_position' => 5, 
        'menu_icon' => true, 
        'can_export' => true, 
        'has_archive' => true, 
        'exclude_from_search' => false, 
        'publicly_queryable' => true, 
        'capability_type' => 'post' 
		);

    register_post_type( 'project', $args); 
}
add_action('init', 'create_project_post_type');

copppy dán vào file function.php khi mở giao diện admin lên chúng ta sẽ được chức năng mới như sau

Tags:

Bình luận

0 bình luận

  • Hãy là người đầu tiên để lại bình luận cho bài viết này!