['type' => 'string', 'max' => 8, 'enum' => ['post', 'page'], 'description' => 'post or page'], 'limit' => ['type' => 'int', 'min' => 1, 'max' => 20, 'optional' => true, 'description' => 'How many items, 1 to 20 (default 10).'], 'search' => ['type' => 'string', 'max' => 100, 'optional' => true, 'description' => 'Optional words to search for in titles and text.'], 'page' => ['type' => 'int', 'min' => 1, 'max' => 50, 'optional' => true, 'description' => 'Which page of results, 1 to 50 (default 1). Use it when has_more is true.'], ]; } public function mutates(): bool { return false; } public function authorizeObject(Principal $principal, array $args): bool { return $principal->siteId === get_current_blog_id(); } public function execute(Principal $principal, array $args): array { $limit = (int) ($args['limit'] ?? 10); $page = (int) ($args['page'] ?? 1); // One extra row is asked for so the client learns whether another page exists without a counting query; the extra row is never returned. $q = new \WP_Query([ 'post_type' => $args['post_type'], 'post_status' => 'publish', 'has_password' => false, 'posts_per_page' => $limit + 1, 'offset' => ($page - 1) * $limit, // Newest first with the ID as a tie-breaker: items that share a timestamp (an import, a scheduled batch) must keep one fixed order, or paging would repeat or skip them. 'orderby' => ['date' => 'DESC', 'ID' => 'DESC'], 'no_found_rows' => true, 'ignore_sticky_posts' => true, 's' => (string) ($args['search'] ?? ''), ]); $items = []; $rows = $q->posts; $more = count($rows) > $limit; foreach (array_slice($rows, 0, $limit) as $p) { $items[] = [ 'id' => (int) $p->ID, 'title' => mb_substr(wp_strip_all_tags(get_the_title($p)), 0, 200), 'url' => (string) get_permalink($p), 'date' => (string) get_post_time('c', true, $p), 'excerpt' => mb_substr(trim((string) preg_replace('/\s+/u', ' ', wp_strip_all_tags(strip_shortcodes((string) $p->post_content)))), 0, 200), ]; } return ['untrusted_text' => true, 'page' => $page, 'has_more' => $more, 'items' => $items]; } }