Creating Custom Post Type WordPress Code: Real-Life Examples & Performance Optimization

tạo custom post type wordpress code

Are you looking for a way to create custom post type wordpress code to expand your website structure without depending on plugins? Self-coding not only provides absolute flexibility but also helps optimize performance significantly. This article from Pham Hai: Personal blog will provide practical examples, explain important parameters and instructions for displaying the frontend in the most professional way, based on today's latest programming standards.

tạo custom post type wordpress code

Why should you create Custom Post Type with code instead of using a plugin?

Creating your own CPT with code gives you complete control over features, reduces database capacity and avoids conflicts compared to installing heavy plugins.

Full control and unlimited customization

Khi áp dụng hướng dẫn tạo custom post type wordpress không dùng plugin, bạn làm chủ hoàn toàn mã nguồn PHP của mình. Thay vì bị giới hạn bởi các tùy chọn có sẵn trên giao diện của một công cụ bên thứ ba, bạn có thể tự do can thiệp sâu vào hệ thống. Việc sử dụng code cho phép bạn dễ dàng thêm, bớt các tính năng thông qua việc cấu hình mảng $args một cách chính xác theo logic nghiệp vụ riêng của dự án.

Optimize performance and reduce website load

Popular CPT creation plugins like CPT UI or Toolset are very convenient, but they often load additional CSS and JavaScript files and execute unnecessary queries into the database. By writing code yourself, you contribute to maximizing performance for the website. Your website will only run the code that is absolutely necessary, keeping the system light and helping to increase page load speed.

Better security and no third-party dependency

Reducing the number of plugins means you are narrowing the attack surface of your website. Source code that you control and write yourself is safer from automated vulnerability scans. Furthermore, you will never have to worry about a plugin losing support for updates or conflicts with a new WordPress version.

Instructions for creating Custom Post Type WordPress with code (Practical example)

Hướng dẫn tạo Custom Post Type WordPress bằng code (Ví dụ thực tế)

Để tạo CPT, bạn cần sử dụng hàm register_post_type kết hợp với hook add_action('init') và đặt đoạn mã PHP vào đúng vị trí trong hệ thống theme hoặc plugin.

Step 1: Determine needs and prepare necessary information

Trước khi bắt tay vào cách tạo custom post type wordpress bằng code, hãy xác định rõ loại nội dung bạn muốn thêm. Đó có thể là "Dự án", "Sản phẩm", "Khóa học" hay "Sự kiện". Bạn cần chuẩn bị sẵn tên định danh (thường gọi là slug), các nhãn hiển thị trong admin menu (labels) và các tính năng mặc định mà bài viết đó sẽ hỗ trợ (supports).

Step 2: Register Custom Post Type in functions.php file

Cách nhanh nhất để bắt đầu là đăng ký custom post type vào functions.php. Tại Phạm Hải: Blog cá nhân, chúng tôi luôn khuyến nghị bạn sử dụng child theme để thực hiện việc này. Nếu bạn viết thẳng vào theme gốc, toàn bộ đoạn code sẽ bị xóa sạch khi bạn cập nhật theme lên phiên bản mới.

Code example to create a complete Custom Post Type "Project".

Dưới đây là ví dụ code tạo custom post type wordpress cho loại bài đăng "Dự án" (Projects). Bạn có thể sao chép đoạn code PHP dưới đây và dán vào cuối file functions.php của child theme:

// Khởi tạo hàm đăng ký CPT
function phamhai_create_project_cpt() {
    // 1. Cấu hình các nhãn hiển thị (Labels)
    $labels = array(
        'name'                  => _x( 'Dự án', 'Post type general name', 'textdomain' ),
        'singular_name'         => _x( 'Dự án', 'Post type singular name', 'textdomain' ),
        'menu_name'             => _x( 'Các Dự án', 'Admin Menu text', 'textdomain' ),
        'add_new'               => __( 'Thêm Dự án mới', 'textdomain' ),
        'add_new_item'          => __( 'Thêm Dự án', 'textdomain' ),
        'edit_item'             => __( 'Sửa Dự án', 'textdomain' ),
        'all_items'             => __( 'Tất cả Dự án', 'textdomain' ),
    );

    // 2. Cấu hình các tham số (Args)
    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array( 'slug' => 'du-an' ), // Đường dẫn tĩnh
        'capability_type'    => 'post',
        'has_archive'        => true, // Cho phép có trang lưu trữ
        'hierarchical'       => false,
        'menu_position'      => 5,
        'supports'           => array( 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields' ),
        'menu_icon'          => 'dashicons-portfolio', // Icon hiển thị
        'show_in_rest'       => true, // Kích hoạt Gutenberg editor
    );

    // 3. Thực thi hàm register_post_type
    register_post_type( 'project', $args );
}

// 4. Móc nối hàm vào hook 'init'
add_action( 'init', 'phamhai_create_project_cpt' );

Giải mã các tham số quan trọng trong hàm register_post_type

Hàm register_post_type nhận vào hai tham số chính: tên định danh và mảng $args. Việc hiểu rõ các tham số registerposttype wordpress là chìa khóa để bạn tùy biến hệ thống theo ý muốn.

Parameter 'labels': Customize the name displayed in the admin page

Mảng labels quyết định cách CPT của bạn giao tiếp với người dùng trên giao diện admin menu. Nó bao gồm các chuỗi văn bản cho nút "Thêm mới", "Chỉnh sửa", "Tất cả bài viết", v.v. Việc cấu hình chi tiết labels giúp khu vực quản trị trở nên thân thiện và chuyên nghiệp hơn, đặc biệt khi bàn giao website cho khách hàng.

Parameters 'public', 'has_archive', 'rewrite': Configure display outside the frontend

Here are three core parameters that determine whether or not your content appears externally:

  • public: Đặt là true để CPT có thể truy cập được cả ở frontend và backend.
  • has_archive: Cấp phép tạo trang lưu trữ (archive page). Nếu true, bạn có thể truy cập danh sách dự án qua đường dẫn domain.com/du-an/.
  • rewrite: Cho phép bạn định dạng lại đường dẫn tĩnh. Thay vì dùng tên gốc là project, bạn có thể đổi slug thành du-an để thân thiện hơn với SEO tại Việt Nam.

Parameter 'supports': Specifies the supported features

Tham số supports khai báo các meta box mặc định sẽ xuất hiện trong trình soạn thảo. Bạn có thể truyền vào một mảng bao gồm: title (tiêu đề), editor (trình soạn thảo nội dung), thumbnail (ảnh đại diện). Đặc biệt, việc thêm custom-fields vào mảng này là bước đệm quan trọng để xây dựng custom post type với custom fields chuyên sâu.

Parameter 'menu_icon': Change the icon for your Custom Post Type

Để admin menu trực quan và dễ phân biệt hơn, bạn nên thay đổi biểu tượng mặc định. WordPress cung cấp sẵn bộ thư viện Dashicons. Bạn chỉ cần tìm icon ưng ý và truyền tên class (ví dụ: dashicons-portfolio hoặc dashicons-store) vào tham số menu_icon.

Expanded functionality for Custom Post Type

To manage and organize data scientifically, you need to combine CPT with taxonomy and custom data fields.

Create Custom Taxonomy for Custom Post Type for classification

Tương tự như Category và Tag của Post mặc định, việc tạo custom taxonomy cho custom post type wordpress (ví dụ: "Loại dự án", "Công nghệ sử dụng") giúp gom nhóm nội dung hiệu quả. Bạn sẽ sử dụng hàm register_taxonomy() và gắn nó vào CPT thông qua hook init.

Taxonomy parameter Meaning Application example
hierarchical => true Works like Category (with parent/child) Classification: Web Project, App Project
hierarchical => false Works like Tag (no parent/child) Technology: PHP, ReactJS, Node
show_admin_column Displays the classification column on the list page Đặt true để dễ quản lý trong admin

Integrate Custom Fields to add detailed information

To store specific data such as "Completion date", "Budget", or "Customer name", combining custom post type with custom fields is the optimal solution. Although WordPress has custom fields available by default, from an expert perspective, we recommend using the Advanced Custom Fields (ACF) or Meta Box plugin to create an intuitive input interface, then use PHP code to call the data out.

How to display Custom Post Type on the frontend

To display custom post types on the frontend, you need to master WordPress Template Hierarchy or use a custom WP_Query loop.

Create separate template files: single-{posttype}.php and archive-{posttype}.php

WordPress tự động nhận diện các file template file theo cấu trúc tên nhất định.

  • Để hiển thị chi tiết một bài viết thuộc CPT "project", bạn hãy tạo file single-project.php.
  • Để hiển thị danh sách tất cả các dự án, bạn tạo file archive-project.php. Bạn có thể copy nội dung từ file single.phparchive.php của theme hiện tại sang các file mới này và tiến hành tùy biến giao diện bằng HTML/CSS.

Use WP_Query to add Custom Post Type to homepage or other pages

Cách thêm custom post type vào trang chủ wordpress hoặc bất kỳ một trang (Page) nào khác là khởi tạo một đối tượng WP_Query mới. Dưới đây là đoạn code mẫu để gọi 6 dự án mới nhất:

<?php
$args = array(
    'post_type'      => 'project', // Gọi đúng tên CPT
    'posts_per_page' => 6,
    'post_status'    => 'publish'
);
$project_query = new WP_Query( $args );

if ( $project_query->have_posts() ) :
    echo '<div class="project-grid">';
    while ( $project_query->have_posts() ) : $project_query->the_post();
        echo '<h3><a href="' . get_permalink() . '">' . get_the_title() . '</a></h3>';
        // Gọi thêm ảnh đại diện, tóm tắt tại đây
    endwhile;
    echo '</div>';
    wp_reset_postdata(); // Rất quan trọng để reset lại query chính
else :
    echo 'Chưa có dự án nào.';
endif;
?>

Performance optimization and best practices

For the system to operate stably and professionally, you need to pay attention to how to organize code, handle paths and avoid data conflicts.

Move code from functions.php to a separate plugin for easy management

Mặc dù viết vào functions.php rất nhanh, nhưng tạo custom post type trong plugin riêng mới là tiêu chuẩn thực hành tốt nhất (best practice). Việc này giúp tách biệt dữ liệu (content) khỏi giao diện (theme). Khi bạn đổi theme mới, toàn bộ dữ liệu CPT đã tạo vẫn được giữ nguyên vẹn trong admin menu mà không bị mất đi. Bạn chỉ cần tạo một thư mục trong wp-content/plugins, tạo một file PHP và thêm phần header chuẩn của plugin WordPress.

Note about naming and "slug" to avoid conflicts

Khi khai báo tên định danh cho $post_type, độ dài tối đa cho phép là 20 ký tự, không được chứa khoảng trắng hay chữ in hoa. Một mẹo nhỏ là hãy luôn thêm tiền tố (prefix) vào tên CPT (ví dụ: ph_project thay vì chỉ dùng project) để tránh xung đột với database của các plugin khác hoặc các tính năng cốt lõi của WordPress.

Update Permalinks after registration or change Custom Post Type

Lỗi phổ biến nhất sau khi tạo CPT là gặp thông báo "Lỗi 404 Not Found" khi người dùng click xem chi tiết bài viết. Để khắc phục, bạn bắt buộc phải cập nhật lại permalinks. Rất đơn giản, bạn chỉ cần truy cập vào Cài đặt > Đường dẫn tĩnh (Settings > Permalinks) trong admin menu và nhấn nút "Lưu thay đổi". Hành động này sẽ ra lệnh cho WordPress flush (làm mới) lại toàn bộ rewrite rules.

Việc tạo custom post type wordpress code thực sự mang lại sự linh hoạt và hiệu suất vượt trội so với việc lạm dụng cài đặt quá nhiều plugin. Bằng cách nắm vững hàm register_post_type, hiểu rõ các tham số cấu hình và cách sử dụng các hook liên quan, bạn có thể xây dựng một cấu trúc dữ liệu tùy chỉnh chuyên nghiệp. Tại Phạm Hải: Blog cá nhân, chúng tôi tin rằng việc làm chủ kỹ năng tự code CPT sẽ giúp website của bạn luôn gọn nhẹ, dễ bảo trì và đáp ứng chính xác mọi yêu cầu phức tạp của các dự án web hiện đại trong năm 2026 này.

If you encounter any difficulties while implementing the above code or need further advice on how to display WordPress data, don't hesitate to leave a comment below. Pham Hai: Personal blog is always ready to support you!

Lưu ý: Thông tin trong bài viết này chỉ mang tính chất tham khảo. Để có được lời khuyên tốt nhất, vui lòng liên hệ trực tiếp với chúng tôi để được tư vấn cụ thể dựa trên nhu cầu thực tế của bạn.

Categories: Digital Marketing Lập Trình WordPress Thương Mại Điện Tử Wordpress

mrhai

Để lại bình luận