WordPress의 사용자 지정 데이터베이스 테이블: 2부

게시 됨: 2022-08-01

WordPress의 사용자 지정 데이터베이스 테이블에 대한 시리즈의 첫 번째 부분에서는 자체 사용자 지정 플러그인 내부에서 사용자 지정 데이터베이스 테이블을 만드는 방법을 살펴보았습니다. 2부에서는 플러그인 삭제 시 사용자 지정 데이터베이스 테이블을 삭제하는 방법을 포함하여 WordPress 사용자 지정 테이블 수정을 수정하는 방법을 안내합니다. 또한 사용자 정의 데이터 테이블에 항목을 보거나 추가하는 옵션과 함께 관리 영역에서 플러그인에 대한 메뉴 항목을 추가하는 방법을 설명합니다.

플러그인 삭제 시 사용자 정의 테이블을 삭제하는 방법

플러그인 자체가 삭제되었을 때 테이블을 삭제하려면 플러그인에 대한 제거 후크를 설정하기 위해 WordPress에서 제공하는 register_uninstall_hook() 함수를 사용해야 합니다.

 function uninstall_students_plugin(){ global $wpdb; $table_name = $wpdb->prefix . 'students'; $wpdb->query("DROP TABLE IF EXISTS $table_name"); } register_uninstall_hook(__FILE__,'uninstall_students_plugin');

지금 플러그인을 비활성화하고 삭제하면 데이터베이스의 "students" 테이블이 성공적으로 삭제된 것을 볼 수 있습니다.

사용자 정의 테이블 관리 메뉴 항목 및 페이지

이 섹션에서는 "students" 사용자 정의 테이블에 대한 메뉴 항목과 함께 관리 페이지를 추가하는 방법을 보여 드리겠습니다.

관리자 메뉴 항목

다음은 시도할 수 있는 코드입니다. 현재 플러그인 PHP 파일에 추가합니다.

 function students_custom_table_admin_menu() { add_menu_page(__('Students', 'students_custom_table'), __('Students', 'students_custom_table'), 'activate_plugins', 'students', 'students_custom_table_page_handler', 'dashicons-welcome-learn-more', '5'); add_submenu_page('students', __('Students', 'students_custom_table'), __('Students', 'students_custom_table'), 'activate_plugins', 'students', 'students_custom_table_page_handler'); add_submenu_page('students', __('Add new', 'students_custom_table'), __('Add new', 'students_custom_table'), 'activate_plugins', 'students_form', 'students_custom_table_page_handler_add_form'); } add_action('admin_menu', 'students_custom_table_admin_menu');

이제 관리 영역에 다음과 같은 항목이 표시되어야 합니다.

예상대로 아이콘을 클릭하면 아무 것도 표시되지 않습니다. 다음 섹션에서 페이지 내용을 정의할 것이지만 먼저 위의 코드 줄을 검토하여 작동 방식을 이해하겠습니다.

Pressidium으로 웹사이트 호스팅

60일 환불 보장

계획 보기

최상위 메뉴 항목과 두 개의 하위 항목을 만들고 싶기 때문에 워드프레스에서 제공하는 add_menu_page() 함수와 add_submenu_page()를 모두 사용했습니다. 이러한 함수는 다음 인수를 허용합니다.

 add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position )
  • $page_title 은 반드시 정의되어야 하며 기본적으로 이 메뉴 항목을 선택할 때 리디렉션되는 페이지의 제목 태그의 첫 번째 부분입니다. 우리의 경우 students_custom_table .
  • $menu_title - 또한 필수 - 메뉴에 사용할 텍스트입니다. 우리는 텍스트로 "학생"을 선택했습니다.
  • $capability 는 사용자가 이 메뉴를 표시하는 데 필요한 기능입니다. 우리의 경우 activate_plugins 권한을 선택했습니다. 기본적으로 수퍼유저 및 관리자에게만 제공됩니다. 귀하의 요구 사항에 맞는 역할 또는 기능을 이해하려면 관련 공식 문서를 참조하십시오.
  • $menu_slug 는 권한 바로 뒤에 오는 students 문자열입니다. 또한 필수이며 고유해야 합니다. Sanitize_key()와 호환되는 소문자 영숫자, 대시 및 밑줄 문자만 사용합니다.
  • $icon_url 은 선택적 인수이며 메뉴 항목에 사용할 아이콘 파일에 연결되는 URL입니다. 우리는 dashicons WordPress 라이브러리에서 하나를 선택했습니다.
  • $position은 이 항목이 나타나야 하는 메뉴 순서에서 선택적으로 위치를 설정하는 곳입니다.
 add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position )

add_menu_page 와 공통되는 매개변수 외에도

  • $parent_slug 매개변수는 상위 메뉴에 필요한 문자열입니다. 이 경우에는 students 입니다.
  • $function 인수는 설정 페이지의 내용을 생성할 콜백 함수를 정의하는 곳입니다. 우리의 경우 학생 표시 테이블의 경우 Students_custom_table_page_handler students_custom_table_page_handler() students_custom_table_page_handler_add_form() 이고 학생을 추가하는 데 사용할 양식의 경우 Students_custom_table_page_handler_add_form() 입니다.
    우리는 아직 이러한 기능을 선언하지 않았지만 잠시 후 선언할 것입니다.

사용자 정의 테이블 레코드 표시

"Students" 메뉴 항목 아래에 Students 테이블을 표시할 코드를 추가하는 것으로 시작하겠습니다.

관리 테이블 데이터를 표시하기 위해 WordPress는 WP_List_Table 내장 클래스를 확장합니다. WP_List_Table 클래스는 wp-admin/includes/class-wp-list-table.php 파일에 개인 클래스로 도입되었습니다. 비공개 클래스는 개발자가 아닌 다른 핵심 클래스 및 기능에서만 사용하기 위한 것이기 때문에 비공개로 명명됩니다.

그러나 WordPress는 이 클래스를 확장하여 재정의할 수 있는 기능을 제공합니다. 따라서 우리가 할 일은 사용자 지정 클래스를 만드는 것입니다. 여기서 WP_List_Table 클래스의 속성과 메서드를 재정의하여 원하는 데이터로 관리 테이블을 채울 것입니다. 클래스 이름을 "Students_Custom_Table_List_Table"로 지정했으며 필요한 코드 줄은 다음과 같습니다.

 if (!class_exists('WP_List_Table')) { require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php'); } class Students_Custom_Table_List_Table extends WP_List_Table { function __construct() { global $status, $page; parent::__construct(array( 'singular' => 'person', 'plural' => 'persons', )); } function column_default($item, $column_name) { return $item[$column_name]; } function column_age($item) { return '<em>' . $item['age'] . '</em>'; } function column_ip($item) { return '<em>' . $item['ip_address'] . '</em>'; } function column_name($item) { $actions = array( 'edit' => sprintf('<a href="?page=students_form&id=%s">%s</a>', $item['id'], __('Edit', 'students_custom_table')), 'delete' => sprintf('<a href="?page=%s&action=delete&id=%s">%s</a>', $_REQUEST['page'], $item['id'], __('Delete', 'students_custom_table')), ); return sprintf('%s %s', $item['name'], $this->row_actions($actions) ); } function column_cb($item) { return sprintf( '<input type="checkbox" name="id[]" value="%s" />', $item['id'] ); } function get_columns() { $columns = array( 'cb' => '<input type="checkbox" />', //Render a checkbox instead of text 'name' => __('Name', 'students_custom_table'), 'email' => __('E-Mail', 'students_custom_table'), 'age' => __('Age', 'students_custom_table'), 'ip_address' => __('IP address', 'students_custom_table'), ); return $columns; } function get_sortable_columns() { $sortable_columns = array( 'name' => array('name', true), 'email' => array('email', false), 'age' => array('age', false), 'ip_address' => array('ip_address', false), ); return $sortable_columns; } function get_bulk_actions() { $actions = array( 'delete' => 'Delete' ); return $actions; } function process_bulk_action() { global $wpdb; $table_name = $wpdb->prefix . 'students'; // do not forget about tables prefix if ('delete' === $this->current_action()) { $ids = isset($_REQUEST['id']) ? $_REQUEST['id'] : array(); if (is_array($ids)) $ids = implode(',', $ids); if (!empty($ids)) { $wpdb->query("DELETE FROM $table_name WHERE id IN($ids)"); } } } function prepare_items() { global $wpdb; $table_name = $wpdb->prefix . 'students'; $per_page = 5; $columns = $this->get_columns(); $hidden = array(); $sortable = $this->get_sortable_columns(); $this->_column_headers = array($columns, $hidden, $sortable); $this->process_bulk_action(); $total_items = $wpdb->get_var("SELECT COUNT(id) FROM $table_name"); $paged = isset($_REQUEST['paged']) ? ($per_page * max(0, intval($_REQUEST['paged']) - 1)) : 0; $orderby = (isset($_REQUEST['orderby']) && in_array($_REQUEST['orderby'], array_keys($this->get_sortable_columns()))) ? $_REQUEST['orderby'] : 'name'; $order = (isset($_REQUEST['order']) && in_array($_REQUEST['order'], array('asc', 'desc'))) ? $_REQUEST['order'] : 'asc'; $this->items = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name ORDER BY $orderby $order LIMIT %d OFFSET %d", $per_page, $paged), ARRAY_A); $this->set_pagination_args(array( 'total_items' => $total_items, 'per_page' => $per_page, 'total_pages' => ceil($total_items / $per_page) )); } }

코드를 주의 깊게 살펴보면 'age' 및 'ip_address' 열이 정의된 방식을 알 수 있습니다. 이제 "학생" 관리 화면의 내용을 최종적으로 제공할 함수를 계속 진행하고 정의할 수 있습니다.

 function students_custom_table_page_handler() { global $wpdb; $table = new Students_Custom_Table_List_Table(); $table->prepare_items(); $message = ''; if ('delete' === $table->current_action()) { $message = '<div class="updated below-h2"><p>' . sprintf(__('Items deleted: %d', 'students_custom_table'), count($_REQUEST['id'])) . '</p></div>'; } ?> <div class="wrap"> <div class="icon32 icon32-posts-post"><br></div> <h2><?php _e('Students', 'students_custom_table')?> <a class="add-new-h2" href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=students_form');?>"><?php _e('Add new', 'students_custom_table')?></a> </h2> <?php echo $message; ?> <form method="GET"> <input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>"/> <?php $table->display() ?> </form> </div> <?php }

간단히 말해서, 우리는 먼저 사용자 정의 Students_Custom_Table_List_Table 클래스의 인스턴스를 만든 다음 학생의 테이블 데이터를 포함할 html 요소를 생성했습니다. 이제 표시된 테이블을 볼 수 있어야 하지만 비어 있다는 점에 유의하십시오.

이제 이 작업을 완료했습니다. 학생을 추가해 보겠습니다.!

사용자 지정 데이터를 추가하기 위한 양식 만들기

앞에서 언급했듯이 학생 추가를 담당하는 함수는 students_custom_table_page_handler_add_form() 입니다.

 function students_custom_table_page_handler_add_form() { global $wpdb; $table_name = $wpdb->prefix . 'students'; $message = ''; $notice = ''; $default = array( 'id' => 0, 'name' => '', 'email' => '', 'age' => null, 'ip_address' => null, ); if (wp_verify_nonce($_REQUEST['nonce'], basename(__FILE__))) { $item = shortcode_atts($default, $_REQUEST); $result = $wpdb->insert($table_name, $item); $item['id'] = $wpdb->insert_id; if ($result) { $message = __('Item was successfully saved', 'students_custom_table'); } else { $notice = __('There was an error while saving item', 'students_custom_table'); } } add_meta_box('students_form_meta_box', 'Student data', 'students_custom_table_students_form_meta_box_handler', 'student', 'normal', 'default'); ?> <div class="wrap"> <div class="icon32 icon32-posts-post"><br></div> <h2><?php _e('Student', 'students_custom_table')?> <a class="add-new-h2" href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=students');?>"><?php _e('back to list', 'students_custom_table')?></a> </h2> <?php if (!empty($notice)): ?> <div class="error"><p><?php echo $notice ?></p></div> <?php endif;?> <?php if (!empty($message)): ?> <div class="updated"><p><?php echo $message ?></p></div> <?php endif;?> <form method="POST"> <input type="hidden" name="nonce" value="<?php echo wp_create_nonce(basename(__FILE__))?>"/> <input type="hidden" name="id" value="<?php echo $item['id'] ?>"/> <div class="metabox-holder"> <div> <div> <?php do_meta_boxes('student', 'normal', $item); ?> <input type="submit" value="<?php _e('Save', 'students_custom_table')?>" class="button-primary" name="submit"> </div> </div> </div> </form> </div> <?php }

코드에서 볼 수 있듯이 먼저 새 레코드에 사용할 $default 배열을 설정합니다.

다음으로 요청이 게시되고 올바른 nonce가 있는지 확인한 후 shortcode_atts()를 사용합니다. 이것은 주어진 매개변수를 결합하고 필요할 때 기본값을 채우는 매우 유용한 내장 WordPress 기능입니다.

마지막으로 사용자 정의 메타 상자를 추가하고 데이터를 사용자 정의 테이블에 삽입하면 프로세스가 성공했음을 알리는 메시지가 수신됩니다.

이 자습서의 목적을 위해 실제 세계에서 사용되는 경우 추가하고 싶은 몇 가지 요소를 건너뛰었습니다. 여기에는 중복 이름이나 이메일이 추가되는 경우 어떻게 되는지 정의하는 것과 같은 작업을 수행하여 데이터베이스에 추가된 정보의 유효성을 검사하는 것이 포함됩니다.

마지막으로 사용자 정의 메타 상자에 대한 핸들러를 추가해야 합니다.

 function students_custom_table_students_form_meta_box_handler($item) { ?> <table cellspacing="2" cellpadding="5" class="form-table"> <tbody> <tr class="form-field"> <th valign="top" scope="row"> <label for="name"><?php _e('Name', 'students_custom_table')?></label> </th> <td> <input name="name" type="text" value="<?php echo esc_attr($item['name'])?>" size="50" class="code" placeholder="<?php _e('Your name', 'students_custom_table')?>" required> </td> </tr> <tr class="form-field"> <th valign="top" scope="row"> <label for="email"><?php _e('E-Mail', 'students_custom_table')?></label> </th> <td> <input name="email" type="email" value="<?php echo esc_attr($item['email'])?>" size="50" class="code" placeholder="<?php _e('Your E-Mail', 'students_custom_table')?>" required> </td> </tr> <tr class="form-field"> <th valign="top" scope="row"> <label for="age"><?php _e('Age', 'students_custom_table')?></label> </th> <td> <input name="age" type="number" value="<?php echo esc_attr($item['age'])?>" size="50" class="code" placeholder="<?php _e('Your age', 'students_custom_table')?>" required> </td> </tr> <tr class="form-field"> <th valign="top" scope="row"> <label for="ip_address"><?php _e('IP', 'students_custom_table')?></label> </th> <td> <input name="ip_address" type="number" value="<?php echo esc_attr($item['ip_address'])?>" size="50" class="code" placeholder="<?php _e('Your IP address', 'students_custom_table')?>" required> </td> </tr> </tbody> </table> <?php }

그리고 그게 다야. 이제 학생을 추가하고, 학생 목록을 보거나, 학생을 삭제하고, 사용자 지정 데이터베이스 테이블에 데이터를 저장할 수 있는 사용자 지정 플러그인이 있습니다!