Files
2026-05-08 03:15:09 +00:00

59 lines
3.2 KiB
PHP

<?php
namespace AskTamMCP\Tools;
defined('ABSPATH') || exit;
class PageTools {
public static function listPages(array $args): array {
$query = new \WP_Query([
'post_type' => 'page',
'post_status' => $args['status'] ?? 'publish',
'posts_per_page' => (int) ($args['per_page'] ?? 20),
'paged' => (int) ($args['page'] ?? 1),
's' => $args['search'] ?? '',
'post_parent' => isset($args['parent']) ? (int) $args['parent'] : '',
]);
$pages = [];
foreach ($query->posts as $p) {
$pages[] = ['id' => $p->ID, 'title' => $p->post_title, 'status' => $p->post_status, 'slug' => $p->post_name, 'link' => get_permalink($p->ID), 'parent' => (int) $p->post_parent];
}
return ['pages' => $pages, 'total' => $query->found_posts];
}
public static function getPage(array $args): array {
$post = get_post((int) $args['page_id']);
if (!$post || $post->post_type !== 'page') throw new \RuntimeException("Page not found: {$args['page_id']}");
return ['id' => $post->ID, 'title' => $post->post_title, 'content' => $post->post_content, 'status' => $post->post_status, 'slug' => $post->post_name, 'link' => get_permalink($post->ID), 'parent' => (int) $post->post_parent, 'template' => get_page_template_slug($post->ID), 'meta' => array_map(fn($v) => count($v) === 1 ? $v[0] : $v, get_post_meta($post->ID))];
}
public static function createPage(array $args): array {
$postId = wp_insert_post(['post_title' => $args['title'], 'post_content' => $args['content'] ?? '', 'post_status' => $args['status'] ?? 'draft', 'post_type' => 'page', 'post_parent' => (int) ($args['parent'] ?? 0), 'post_name' => $args['slug'] ?? '', 'page_template' => $args['template'] ?? ''], true);
if (is_wp_error($postId)) throw new \RuntimeException($postId->get_error_message());
if (!empty($args['meta'])) foreach ($args['meta'] as $k => $v) update_post_meta($postId, $k, $v);
return ['id' => $postId, 'link' => get_permalink($postId)];
}
public static function updatePage(array $args): array {
$pageId = (int) $args['page_id'];
$data = ['ID' => $pageId];
if (isset($args['title'])) $data['post_title'] = $args['title'];
if (isset($args['content'])) $data['post_content'] = $args['content'];
if (isset($args['status'])) $data['post_status'] = $args['status'];
if (isset($args['parent'])) $data['post_parent'] = (int) $args['parent'];
if (isset($args['template'])) $data['page_template'] = $args['template'];
$result = wp_update_post($data, true);
if (is_wp_error($result)) throw new \RuntimeException($result->get_error_message());
if (!empty($args['meta'])) foreach ($args['meta'] as $k => $v) update_post_meta($pageId, $k, $v);
return ['id' => $pageId, 'updated' => true];
}
public static function deletePage(array $args): array {
$result = wp_delete_post((int) $args['page_id'], (bool) ($args['force'] ?? false));
if (!$result) throw new \RuntimeException("Failed to delete page: {$args['page_id']}");
return ['id' => (int) $args['page_id'], 'deleted' => true];
}
}