您提供的实现看起来已经非常完整,涵盖了插件初始化、自定义表的创建、自定义文章类型的注册、分类数据的管理以及数据的保存和后台菜单的添加。以下是完整的代码实现:
<?php
/**
* Plugin Name: Custom Post Plugin
* Description: 一个自定义插件,用于管理自定义文章和分类。
* Version: 1.0
* Author: Your Name
* License: GPL2
*/
// 插件激活时执行初始化
register_activation_hook( __FILE__, 'custom_post_plugin_activate' );
// 插件停用时执行清理工作
register_deactivation_hook( __FILE__, 'custom_post_plugin_deactivate' );
// 插件初始化(创建表和添加随机分类数据)
function custom_post_plugin_activate() {
// 创建自定义表
create_custom_categories_table();
create_custom_post_table();
// 插入一些随机的分类数据
add_random_categories();
}
// 插件停用时执行清理工作
function custom_post_plugin_deactivate() {
// 停用时可以选择删除自定义表,或者保留数据
// delete_custom_categories_table();
// delete_custom_post_table();
}
// 创建 custom_categories 表,用于存储自定义分类
function create_custom_categories_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'custom_categories';
$charset_collate = $wpdb->get_charset_collate();
// 创建自定义分类表,支持父子分类
$sql = "CREATE TABLE $table_name (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL,
parent_id BIGINT(20) UNSIGNED DEFAULT 0,
PRIMARY KEY (id),
KEY parent_id (parent_id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
// 创建 custom_post_table 表,用于存储文章数据
function create_custom_post_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'custom_post_table';
$charset_collate = $wpdb->get_charset_collate();
// 创建自定义文章表
$sql = "CREATE TABLE $table_name (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
post_title VARCHAR(255) NOT NULL,
post_content TEXT NOT NULL,
category_id BIGINT(20) UNSIGNED DEFAULT 0,
PRIMARY KEY (id),
KEY category_id (category_id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
// 插入随机分类数据
function add_random_categories() {
global $wpdb;
$categories = [
['name' => 'Technology', 'slug' => 'technology', 'parent_id' => 0],
['name' => 'Web Development', 'slug' => 'web-development', 'parent_id' => 1],
['name' => 'PHP', 'slug' => 'php', 'parent_id' => 2],
['name' => 'JavaScript', 'slug' => 'javascript', 'parent_id' => 2],
['name' => 'Design', 'slug' => 'design', 'parent_id' => 0],
['name' => 'UI/UX', 'slug' => 'ui-ux', 'parent_id' => 5],
['name' => 'WordPress', 'slug' => 'wordpress', 'parent_id' => 1],
];
foreach ( $categories as $category ) {
$wpdb->insert(
$wpdb->prefix . 'custom_categories',
array(
'name' => $category['name'],
'slug' => $category['slug'],
'parent_id' => $category['parent_id'],
),
array( '%s', '%s', '%d' )
);
}
}
// 注册自定义 Post Type
function register_custom_post_type() {
$args = array(
'labels' => array(
'name' => '自定义文章',
'singular_name' => '自定义文章',
),
'public' => true,
'has_archive' => true,
'show_ui' => true,
'show_in_rest' => true, // 支持 Gutenberg 编辑器
'supports' => array( 'title', 'editor' ),
);
register_post_type( 'custom_post', $args );
}
add_action( 'init', 'register_custom_post_type' );
// 添加 Metabox
function add_custom_post_meta_box() {
add_meta_box(
'custom_category_meta_box', // 唯一 ID
'选择分类', // Metabox 标题
'render_category_select_box', // 回调函数
'custom_post', // 仅对 custom_post 类型生效
'side', // 显示位置
'default' // 优先级
);
}
add_action( 'add_meta_boxes', 'add_custom_post_meta_box' );
// 渲染分类选择框
function render_category_select_box( $post ) {
global $wpdb;
// 获取所有自定义分类
$categories = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}custom_categories ORDER BY parent_id, name" );
// 构建分类层级
$categories_hierarchy = build_category_hierarchy( $categories );
// 获取当前文章的分类 ID
$current_category = get_post_meta( $post->ID, '_custom_category_id', true );
echo '<select name="custom_category_id" id="custom_category_id">';
echo '<option value="0">无分类</option>';
foreach ( $categories_hierarchy as $category ) {
$selected = ( $current_category == $category->id ) ? 'selected' : '';
echo '<option value="' . $category->id . '" ' . $selected . '>' . str_repeat( ' ', $category->level ) . $category->name . '</option>';
}
echo '</select>';
}
// 构建父子分类层级
function build_category_hierarchy( $categories, $parent_id = 0, $level = 0 ) {
$hierarchy = [];
foreach ( $categories as $category ) {
if ( $category->parent_id == $parent_id ) {
$category->level = $level; // 设置分类层级
$hierarchy[] = $category;
// 递归获取子分类
$hierarchy = array_merge( $hierarchy, build_category_hierarchy( $categories, $category->id, $level + 1 ) );
}
}
return $hierarchy;
}
// 保存自定义数据到自定义表
function save_custom_post_data( $post_id ) {
// 防止递归调用
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return $post_id;
// 确保是在正确的 post type 上
if ( get_post_type( $post_id ) != 'custom_post' ) return $post_id;
// 获取提交的数据
$new_title = sanitize_text_field( $_POST['post_title'] );
$new_content = sanitize_textarea_field( $_POST['post_content'] );
$new_category_id = isset( $_POST['custom_category_id'] ) ? intval( $_POST['custom_category_id'] ) : 0;
// 获取自定义表名
global $wpdb;
$table_name = $wpdb->prefix . 'custom_post_table';
// 插入或更新自定义表中的数据
$existing_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table_name WHERE id = %d", $post_id ) );
if ( $existing_post ) {
// 更新自定义表中的数据
$wpdb->update(
$table_name,
array(
'post_title' => $new_title,
'post_content' => $new_content,
'category_id' => $new_category_id
),
array( 'id' => $post_id ),
array( '%s', '%s', '%d' ),
array( '%d' )
);
} else {
// 插入新数据
$wpdb->insert(
$table_name,
array(
'id' => $post_id,
'post_title' => $new_title,
'post_content' => $new_content,
'category_id' => $new_category_id
),
array( '%d', '%s', '%s', '%d' )
);
}
return $post_id;
}
add_action( 'save_post', 'save_custom_post_data' );
// 注册菜单
function custom_post_menu() {
add_menu_page(
'自定义文章', // 页面标题
'自定义文章', // 菜单标题
'manage_options', // 权限
'custom_post_page', // 菜单别名
'custom_post_edit_page' // 显示内容的函数
);
}
add_action( 'admin_menu', 'custom_post_menu' );
// 显示内容的函数
function custom_post_edit_page() {
echo '<div class="wrap">';
echo '<h1>自定义文章管理</h1>';
echo '<p>这里是自定义文章的管理页面。</p>';
echo '</div>';
}
这个插件实现了以下功能:
- 插件初始化:在插件激活时创建自定义表
custom_categories
和custom_post_table
,并插入一些随机的分类数据。 - 自定义 Post Type:注册了一个名为
custom_post
的自定义文章类型。 - Metabox:在自定义文章编辑页面添加了一个 Metabox,用于选择分类。
- 保存数据:通过
save_post
钩子将文章数据保存到自定义表中。 - 后台菜单:添加了一个后台菜单项,用于管理自定义文章。
您可以将这段代码保存为一个 PHP 文件,并将其放置在 WordPress 插件目录中,然后在 WordPress 管理后台中激活插件。
为了使用 WP_List_Table
来管理自定义文章数据,我们需要创建一个自定义的列表表格类,并在后台菜单页面中使用它。以下是完整的实现步骤:
- 创建自定义列表表格类:继承
WP_List_Table
并实现必要的方法。 - 在后台菜单页面中使用这个表格类:显示自定义文章数据。
完整实现
<?php
/**
* Plugin Name: Custom Post Plugin
* Description: 一个自定义插件,用于管理自定义文章和分类。
* Version: 1.0
* Author: Your Name
* License: GPL2
*/
// 插件激活时执行初始化
register_activation_hook( __FILE__, 'custom_post_plugin_activate' );
// 插件停用时执行清理工作
register_deactivation_hook( __FILE__, 'custom_post_plugin_deactivate' );
// 插件初始化(创建表和添加随机分类数据)
function custom_post_plugin_activate() {
// 创建自定义表
create_custom_categories_table();
create_custom_post_table();
// 插入一些随机的分类数据
add_random_categories();
}
// 插件停用时执行清理工作
function custom_post_plugin_deactivate() {
// 停用时可以选择删除自定义表,或者保留数据
// delete_custom_categories_table();
// delete_custom_post_table();
}
// 创建 custom_categories 表,用于存储自定义分类
function create_custom_categories_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'custom_categories';
$charset_collate = $wpdb->get_charset_collate();
// 创建自定义分类表,支持父子分类
$sql = "CREATE TABLE $table_name (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL,
parent_id BIGINT(20) UNSIGNED DEFAULT 0,
PRIMARY KEY (id),
KEY parent_id (parent_id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
// 创建 custom_post_table 表,用于存储文章数据
function create_custom_post_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'custom_post_table';
$charset_collate = $wpdb->get_charset_collate();
// 创建自定义文章表
$sql = "CREATE TABLE $table_name (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
post_title VARCHAR(255) NOT NULL,
post_content TEXT NOT NULL,
category_id BIGINT(20) UNSIGNED DEFAULT 0,
PRIMARY KEY (id),
KEY category_id (category_id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
// 插入随机分类数据
function add_random_categories() {
global $wpdb;
$categories = [
['name' => 'Technology', 'slug' => 'technology', 'parent_id' => 0],
['name' => 'Web Development', 'slug' => 'web-development', 'parent_id' => 1],
['name' => 'PHP', 'slug' => 'php', 'parent_id' => 2],
['name' => 'JavaScript', 'slug' => 'javascript', 'parent_id' => 2],
['name' => 'Design', 'slug' => 'design', 'parent_id' => 0],
['name' => 'UI/UX', 'slug' => 'ui-ux', 'parent_id' => 5],
['name' => 'WordPress', 'slug' => 'wordpress', 'parent_id' => 1],
];
foreach ( $categories as $category ) {
$wpdb->insert(
$wpdb->prefix . 'custom_categories',
array(
'name' => $category['name'],
'slug' => $category['slug'],
'parent_id' => $category['parent_id'],
),
array( '%s', '%s', '%d' )
);
}
}
// 注册自定义 Post Type
function register_custom_post_type() {
$args = array(
'labels' => array(
'name' => '自定义文章',
'singular_name' => '自定义文章',
),
'public' => true,
'has_archive' => true,
'show_ui' => true,
'show_in_rest' => true, // 支持 Gutenberg 编辑器
'supports' => array( 'title', 'editor' ),
);
register_post_type( 'custom_post', $args );
}
add_action( 'init', 'register_custom_post_type' );
// 添加 Metabox
function add_custom_post_meta_box() {
add_meta_box(
'custom_category_meta_box', // 唯一 ID
'选择分类', // Metabox 标题
'render_category_select_box', // 回调函数
'custom_post', // 仅对 custom_post 类型生效
'side', // 显示位置
'default' // 优先级
);
}
add_action( 'add_meta_boxes', 'add_custom_post_meta_box' );
// 渲染分类选择框
function render_category_select_box( $post ) {
global $wpdb;
// 获取所有自定义分类
$categories = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}custom_categories ORDER BY parent_id, name" );
// 构建分类层级
$categories_hierarchy = build_category_hierarchy( $categories );
// 获取当前文章的分类 ID
$current_category = get_post_meta( $post->ID, '_custom_category_id', true );
echo '<select name="custom_category_id" id="custom_category_id">';
echo '<option value="0">无分类</option>';
foreach ( $categories_hierarchy as $category ) {
$selected = ( $current_category == $category->id ) ? 'selected' : '';
echo '<option value="' . $category->id . '" ' . $selected . '>' . str_repeat( ' ', $category->level ) . $category->name . '</option>';
}
echo '</select>';
}
// 构建父子分类层级
function build_category_hierarchy( $categories, $parent_id = 0, $level = 0 ) {
$hierarchy = [];
foreach ( $categories as $category ) {
if ( $category->parent_id == $parent_id ) {
$category->level = $level; // 设置分类层级
$hierarchy[] = $category;
// 递归获取子分类
$hierarchy = array_merge( $hierarchy, build_category_hierarchy( $categories, $category->id, $level + 1 ) );
}
}
return $hierarchy;
}
// 保存自定义数据到自定义表
function save_custom_post_data( $post_id ) {
// 防止递归调用
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return $post_id;
// 确保是在正确的 post type 上
if ( get_post_type( $post_id ) != 'custom_post' ) return $post_id;
// 获取提交的数据
$new_title = sanitize_text_field( $_POST['post_title'] );
$new_content = sanitize_textarea_field( $_POST['post_content'] );
$new_category_id = isset( $_POST['custom_category_id'] ) ? intval( $_POST['custom_category_id'] ) : 0;
// 获取自定义表名
global $wpdb;
$table_name = $wpdb->prefix . 'custom_post_table';
// 插入或更新自定义表中的数据
$existing_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table_name WHERE id = %d", $post_id ) );
if ( $existing_post ) {
// 更新自定义表中的数据
$wpdb->update(
$table_name,
array(
'post_title' => $new_title,
'post_content' => $new_content,
'category_id' => $new_category_id
),
array( 'id' => $post_id ),
array( '%s', '%s', '%d' ),
array( '%d' )
);
} else {
// 插入新数据
$wpdb->insert(
$table_name,
array(
'id' => $post_id,
'post_title' => $new_title,
'post_content' => $new_content,
'category_id' => $new_category_id
),
array( '%d', '%s', '%s', '%d' )
);
}
return $post_id;
}
add_action( 'save_post', 'save_custom_post_data' );
// 注册菜单
function custom_post_menu() {
add_menu_page(
'自定义文章', // 页面标题
'自定义文章', // 菜单标题
'manage_options', // 权限
'custom_post_page', // 菜单别名
'custom_post_edit_page' // 显示内容的函数
);
}
add_action( 'admin_menu', 'custom_post_menu' );
// 显示内容的函数
function custom_post_edit_page() {
// 创建表格实例
$custom_post_table = new Custom_Post_List_Table();
$custom_post_table->prepare_items();
echo '<div class="wrap">';
echo '<h1>自定义文章管理</h1>';
$custom_post_table->display();
echo '</div>';
}
// 自定义列表表格类
if( ! class_exists( 'WP_List_Table' ) ) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class Custom_Post_List_Table extends WP_List_Table {
function __construct() {
parent::__construct( array(
'singular' => 'custom_post',
'plural' => 'custom_posts',
'ajax' => false
) );
}
function get_columns() {
return array(
'cb' => '<input type="checkbox" />',
'id' => 'ID',
'post_title' => '标题',
'category_id' => '分类ID',
);
}
function prepare_items() {
global $wpdb;
$table_name = $wpdb->prefix . 'custom_post_table';
$per_page = 10;
$current_page = $this->get_pagenum();
$total_items = $wpdb->get_var( "SELECT COUNT(id) FROM $table_name" );
$this->set_pagination_args( array(
'total_items' => $total_items,
'per_page' => $per_page
) );
$this->items = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM $table_name ORDER BY id DESC LIMIT %d OFFSET %d",
$per_page,
($current_page - 1) * $per_page
),
ARRAY_A
);
}
function column_default( $item, $column_name ) {
return $item[ $column_name ];
}
function column_cb( $item ) {
return sprintf(
'<input type="checkbox" name="custom_post[]" value="%s" />', $item['id']
);
}
function column_post_title( $item ) {
$actions = array(
'edit' => sprintf( '<a href="?page=%s&action=%s&post=%s">编辑</a>', $_REQUEST['page'], 'edit', $item['id'] ),
'delete' => sprintf( '<a href="?page=%s&action=%s&post=%s">删除</a>', $_REQUEST['page'], 'delete', $item['id'] ),
);
return sprintf( '%1$s %2$s', $item['post_title'], $this->row_actions( $actions ) );
}
function get_bulk_actions() {
return array(
'delete' => '删除'
);
}
function process_bulk_action() {
global $wpdb;
$table_name = $wpdb->prefix . 'custom_post_table';
if ( 'delete' === $this->current_action() ) {
$ids = isset( $_GET['custom_post'] ) ? $_GET['custom_post'] : array();
if ( is_array( $ids ) ) {
$ids = implode( ',', array_map( 'intval', $ids ) );
$wpdb->query( "DELETE FROM $table_name WHERE id IN ($ids)" );
}
}
}
}
解释
- 自定义列表表格类:
Custom_Post_List_Table
继承自WP_List_Table
,用于显示自定义文章数据。
get_columns()
:定义表格列。prepare_items()
:准备表格数据,包括分页。column_default()
:默认列显示。column_cb()
:复选框列。column_post_title()
:标题列,包含操作链接。get_bulk_actions()
:定义批量操作。process_bulk_action()
:处理批量操作。- 后台菜单页面:在
custom_post_edit_page()
中创建表格实例并显示。
- 后台菜单页面:在
这样,您就可以在 WordPress 后台管理自定义文章数据了。