Cách tạo Custom post type trong wordpress - WebService247WebService247

Cách tạo Custom post type trong wordpress

Blogs > Cách tạo Custom post type trong wordpress

Custom Post Type (CPT) là một tính năng của WordPress cho phép bạn tạo các loại bài viết tùy chỉnh bên cạnh bài viết (post) và trang (page) mặc định. Nó giống như một “hộp đựng” mới để tổ chức nội dung đặc thù của bạn.

  • Trước tiên tạo 1 class khái quát để sử dụng cho nhiều post type
class WS__Post_Type {
    private $post_type;
    private $singular_name;
    private $plural_name;
    private $args;
    private $meta_boxes;

    public function __construct($post_type, $singular_name, $plural_name, $args = [], $meta_boxes = []) {
        $this->post_type = $post_type;
        $this->singular_name = $singular_name;
        $this->plural_name = $plural_name;
        $this->args = $args;
        $this->meta_boxes = $meta_boxes;

        add_theme_support('post-thumbnails');

        add_action('init', [$this, 'register_post_type']);
        add_action('add_meta_boxes', [$this, 'add_meta_boxes']);
        add_action('save_post', [$this, 'save_meta_data']);
        add_filter("manage_{$this->post_type}_posts_columns", [$this, 'add_columns']);
        add_action("manage_{$this->post_type}_posts_custom_column", [$this, 'render_column_content'], 10, 2);
    }

    public function register_post_type() {
        $default_labels = [
            'name' => $this->plural_name,
            'singular_name' => $this->singular_name,
            'add_new' => 'Add New',
            'add_new_item' => "Add New {$this->singular_name}",
            'edit_item' => "Edit {$this->singular_name}",
            'new_item' => "New {$this->singular_name}",
            'view_item' => "View {$this->singular_name}",
            'search_items' => "Search {$this->plural_name}",
            'not_found' => "No {$this->plural_name} found",
            'not_found_in_trash' => "No {$this->plural_name} found in Trash",
            'all_items' => "All {$this->plural_name}",
            'menu_name' => $this->plural_name,
            'name_admin_bar' => $this->singular_name
        ];

        $default_args = [
            'labels' => $default_labels,
            'public' => true,
            'supports' => ['title', 'editor', 'thumbnail', 'excerpt'],
            'menu_icon' => 'dashicons-admin-post',
            'rewrite' => ['slug' => $this->post_type, 'with_front' => false],
            'has_archive' => false,
            'show_ui' => true,
            'show_in_menu' => true,
            'show_in_nav_menus' => true,
            'publicly_queryable' => true,
        ];

        register_post_type($this->post_type, array_merge($default_args, $this->args));
    }

    public function add_meta_boxes() {
        foreach ($this->meta_boxes as $meta_box) {
            add_meta_box(
                "{$this->post_type}_{$meta_box['id']}_meta_box",
                $meta_box['title'],
                [$this, 'render_meta_box'],
                $this->post_type,
                $meta_box['context'] ?? 'side',
                $meta_box['priority'] ?? 'high',
                $meta_box
            );
        }
    }

    public function render_meta_box($post, $meta_box) {
        $meta_key = $meta_box['args']['meta_key'];
        $value = get_post_meta($post->ID, $meta_key, true);
        wp_nonce_field("{$this->post_type}_save_{$meta_key}", "{$this->post_type}_{$meta_key}_nonce");

        switch ($meta_box['args']['type']) {
            case 'select':
                echo "<label for='{$meta_key}'>{$meta_box['args']['label']}:</label>";
                echo "<select id='{$meta_key}' name='{$meta_key}' style='width: 100%;'>";
                foreach ($meta_box['args']['options'] as $option_value => $option_label) {
                    echo "<option value='{$option_value}' " . selected($value, $option_value, false) . ">{$option_label}</option>";
                }
                echo "</select>";
                break;
            case 'number':
                echo "<label for='{$meta_key}'>{$meta_box['args']['label']}:</label>";
                echo "<input type='number' id='{$meta_key}' name='{$meta_key}' value='" . esc_attr($value) . "' style='width: 100%;' min='0'>";
                break;
        }
    }

    public function save_meta_data($post_id) {
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        foreach ($this->meta_boxes as $meta_box) {
            $meta_key = $meta_box['meta_key'];
            $nonce = "{$this->post_type}_{$meta_key}_nonce";

            if (!isset($_POST[$nonce]) || !wp_verify_nonce($_POST[$nonce], "{$this->post_type}_save_{$meta_key}")) {
                continue;
            }

            if (isset($_POST[$meta_key])) {
                update_post_meta($post_id, $meta_key, sanitize_text_field($_POST[$meta_key]));
            }
        }
    }

    public function add_columns($columns) {
        unset($columns['date']);
        $new_columns = [
            'cb' => $columns['cb'],
            'title' => __('Title'),
            'thumbnail' => __('Thumbnail'),
        ];

        foreach ($this->meta_boxes as $meta_box) {
            $new_columns[$meta_box['id']] = $meta_box['title'];
        }

        $new_columns['excerpt'] = __('Description');
        return $new_columns;
    }

    public function render_column_content($column, $post_id) {
        switch ($column) {
            case 'thumbnail':
                if (has_post_thumbnail($post_id)) {
                    echo get_the_post_thumbnail($post_id, [50, 50]);
                } else {
                    echo '<span>--</span>'; 
                }
                break;
            case 'excerpt':
                $excerpt = get_the_excerpt($post_id);
                echo '<div style="display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;">' . esc_html($excerpt) . '</div>';
                break;
            default:
                foreach ($this->meta_boxes as $meta_box) {
                    if ($column === $meta_box['id']) {
                        $meta_key = $meta_box['meta_key'];
                        $value = get_post_meta($post_id, $meta_key, true);

                        if ($meta_box['type'] === 'number') {
                            echo !empty($value) ? esc_html(number_format($value, 0, ',', '.')) . ' đ' : '--';
                        } elseif ($meta_box['type'] === 'select') {
                            echo !empty($value) && isset($meta_box['options'][$value]) ? esc_html($meta_box['options'][$value]) : 'Không xác định';
                        } else {
                            echo !empty($value) ? esc_html($value) : '--';
                        }
                        break;
                    }
                }
                break;
        }
    }
}
  • Bây giờ ví dụ tôi muốn tạo post type ‘ws_device’ với các thuộc tính name, loại, giá, mô tả thì khởi tạo class có dạng như sau
$device_meta_boxes = [
    [
        'id' => 'type',
        'title' => 'Loại sự kiện',
        'meta_key' => 'ws_type',
        'type' => 'select',
        'label' => 'Chọn loại',
        'options' => [
            'event' => 'Event',
            'teambuilding' => 'Teambuilding'
        ]
    ],
    [
        'id' => 'price',
        'title' => 'Giá thiết bị',
        'meta_key' => 'ws_price',
        'type' => 'number',
        'label' => 'Nhập giá'
    ]
];

new WS__Post_Type(
    'ws_device',
    'Dụng cụ',
    'Dụng cụ',
    ['menu_icon' => 'dashicons-hammer', 'rewrite' => ['slug' => 'ws-device']],
    $device_meta_boxes
);
  • Kết quả như sau: