*/ public static function defaults(): array { return array( 'enabled' => true, 'org_name' => '', 'org_type' => 'Organization', 'force_output' => false, // The entity layer: everything that turns a name into something a // knowledge graph can resolve. See Services\Identity. 'identity' => Services\Identity::defaults(), ); } public function register( Container $container ): void {} public function boot( Container $container ): void { add_action( 'rest_api_init', array( $this, 'routes' ) ); $settings = $this->options()->get( 'schema', self::defaults() ); $active = ! empty( $settings['enabled'] ) && ( null === SeoModule::conflict() || ! empty( $settings['force_output'] ) ); if ( $active ) { Guard::action( 'wp_head', array( $this, 'output' ), 6 ); // Any content change invalidates that post's cached graph; edits // can also change archive pages, so those expire by TTL. add_action( 'save_post', static function ( int $post_id ): void { delete_transient( 'airanksuite_schema_p' . $post_id ); } ); add_action( 'updated_option', static function ( string $option ): void { if ( str_starts_with( $option, 'airanksuite_' ) ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE option_name LIKE %s OR option_name LIKE %s', $wpdb->options, $wpdb->esc_like( '_transient_airanksuite_schema_' ) . '%', $wpdb->esc_like( '_transient_timeout_airanksuite_schema_' ) . '%' ) ); } } ); } } /** * The graph for the home page plus the newest post, with a validation * roll-up. Runs the real builder, so what is shown is what is shipped. */ public function live_graph(): WP_REST_Response { $samples = array(); $home_graph = $this->graph(); $samples[] = array( 'label' => __( 'Home page', 'ai-rank-suite' ), 'url' => home_url( '/' ), 'graph' => $home_graph, ); $recent = get_posts( array( 'numberposts' => 1, 'post_status' => 'publish' ) ); if ( ! empty( $recent ) ) { $samples[] = array( 'label' => __( 'Latest post', 'ai-rank-suite' ), 'url' => (string) get_permalink( $recent[0] ), 'graph' => $this->graph( $recent[0] ), ); } foreach ( $samples as $i => $sample ) { $types = array(); $issues = array(); foreach ( (array) $sample['graph'] as $node ) { foreach ( (array) ( $node['@type'] ?? array() ) as $type ) { $types[] = (string) $type; } // The four fields Google's Rich Results test insists on. $node_type = (array) ( $node['@type'] ?? array() ); if ( array_intersect( array( 'Article', 'BlogPosting', 'NewsArticle' ), $node_type ) ) { foreach ( array( 'headline', 'image', 'publisher', 'datePublished' ) as $required ) { if ( empty( $node[ $required ] ) ) { $issues[] = sprintf( /* translators: 1: schema field, 2: node type */ __( 'Missing “%1$s” on %2$s', 'ai-rank-suite' ), $required, implode( '/', $node_type ) ); } } } if ( in_array( 'Product', $node_type, true ) ) { $has_id = ! empty( $node['gtin'] ) || ! empty( $node['gtin13'] ) || ! empty( $node['gtin12'] ) || ! empty( $node['gtin8'] ) || ! empty( $node['gtin14'] ) || ! empty( $node['mpn'] ) || ! empty( $node['isbn'] ); if ( ! $has_id ) { $issues[] = __( 'Product has no global identifier (gtin, mpn or isbn)', 'ai-rank-suite' ); } if ( empty( $node['offers']['shippingDetails'] ) ) { $issues[] = __( 'Offer is missing shippingDetails', 'ai-rank-suite' ); } if ( empty( $node['offers']['hasMerchantReturnPolicy'] ) ) { $issues[] = __( 'Offer is missing hasMerchantReturnPolicy', 'ai-rank-suite' ); } } } $samples[ $i ]['types'] = array_values( array_unique( $types ) ); $samples[ $i ]['issues'] = array_values( array_unique( $issues ) ); $samples[ $i ]['json'] = (string) wp_json_encode( array( '@context' => 'https://schema.org', '@graph' => $sample['graph'] ), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); unset( $samples[ $i ]['graph'] ); } return new WP_REST_Response( array( 'samples' => $samples, 'validators' => array( array( 'label' => 'Google Rich Results Test', 'url' => 'https://search.google.com/test/rich-results?url=' . rawurlencode( home_url( '/' ) ), ), array( 'label' => 'Schema.org Validator', 'url' => 'https://validator.schema.org/#url=' . rawurlencode( home_url( '/' ) ), ), ), ) ); } /** * Emit the JSON-LD graph. */ public function output(): void { // Fragment cache: building the graph touches settings, post meta, // templates and image sizes on every page view. Singular views cache // per post; archives per URL hash. Invalidated on save_post and on // any schema settings change (see boot()). $key = is_singular() && get_queried_object_id() ? 'airanksuite_schema_p' . get_queried_object_id() : 'airanksuite_schema_u' . md5( \AiRankSuite\Support\Server::path() ); $graph = get_transient( $key ); if ( ! is_array( $graph ) ) { $graph = $this->graph(); set_transient( $key, $graph, HOUR_IN_SECONDS * 12 ); } if ( empty( $graph ) ) { return; } $payload = array( '@context' => 'https://schema.org', '@graph' => $graph, ); // No flags: the defaults escape every slash, so a "" inside a // headline cannot close the element, and non-ASCII text travels as // \u escapes. Both are plain JSON to every consumer of structured data. echo '' . "\n"; } /** * Build the graph for the current request. * * @return array> */ public function graph( ?WP_Post $for_post = null ): array { $settings = $this->options()->get( 'schema', self::defaults() ); $home = home_url( '/' ); $org_name = '' !== (string) $settings['org_name'] ? (string) $settings['org_name'] : get_bloginfo( 'name' ); $org_id = $home . '#organization'; $site_id = $home . '#website'; $org_type = in_array( (string) $settings['org_type'], Services\Identity::type_values(), true ) ? (string) $settings['org_type'] : 'Organization'; $identity_settings = (array) ( $settings['identity'] ?? array() ); // A dedicated logo beats the site icon: the icon is a favicon, and a // 32px favicon in a Knowledge Panel is how a brand looks accidental. $org_logo = (string) ( $identity_settings['logo'] ?? '' ); $graph = array(); $graph[] = array_merge( array_filter( array( '@type' => $org_type, '@id' => $org_id, 'name' => $org_name, 'url' => $home, 'logo' => ( '' !== $org_logo ? $org_logo : get_site_icon_url( 512 ) ) ?: null, ) ), Services\Identity::properties( $identity_settings ) ); $graph[] = array( '@type' => 'WebSite', '@id' => $site_id, 'name' => get_bloginfo( 'name' ), 'url' => $home, 'publisher' => array( '@id' => $org_id ), ); // An explicit post lets REST render exactly what a visitor would get; // on the front end the queried object is the source of truth. if ( null === $for_post && ! is_singular() ) { /** This filter is documented at the end of this method. */ return (array) apply_filters( 'airanksuite/schema/graph', $graph, null ); } $post = $for_post ?? get_queried_object(); if ( ! $post instanceof WP_Post ) { /** This filter is documented at the end of this method. */ return (array) apply_filters( 'airanksuite/schema/graph', $graph, null ); } $url = (string) get_permalink( $post ); $page_id = $url . '#webpage'; $desc = (string) get_post_meta( $post->ID, '_airanksuite_seo_desc', true ); if ( '' === $desc ) { $desc = get_the_excerpt( $post ); } $page = array_filter( array( '@type' => 'page' === $post->post_type ? 'WebPage' : 'Article', '@id' => $page_id, 'url' => $url, 'name' => wp_strip_all_tags( get_the_title( $post ) ), 'headline' => wp_strip_all_tags( get_the_title( $post ) ), 'description' => '' !== $desc ? wp_strip_all_tags( $desc ) : null, 'isPartOf' => array( '@id' => $site_id ), 'datePublished' => get_post_time( 'c', true, $post ) ?: null, 'dateModified' => get_post_modified_time( 'c', true, $post ) ?: null, 'image' => get_the_post_thumbnail_url( $post, 'large' ) ?: null, 'inLanguage' => get_bloginfo( 'language' ), ) ); $author = get_the_author_meta( 'display_name', (int) $post->post_author ); if ( '' !== $author && 'page' !== $post->post_type ) { $page['author'] = array( '@type' => 'Person', 'name' => $author, ); $page['publisher'] = array( '@id' => $org_id ); } $graph[] = $page; $crumbs = $this->breadcrumb_items( $post, $home, $url ); if ( count( $crumbs ) > 1 ) { $graph[] = array( '@type' => 'BreadcrumbList', '@id' => $url . '#breadcrumb', 'itemListElement' => $crumbs, ); } // Per-page schema items plus any matching global template. foreach ( ( new Services\SchemaBuilder() )->build_for_post( $post, $url, $org_id, $site_id ) as $node ) { $graph[] = $node; } $raw = get_post_meta( $post->ID, '_airanksuite_faq', true ); $faqs = is_string( $raw ) && '' !== $raw ? json_decode( $raw, true ) : null; if ( is_array( $faqs ) && ! empty( $faqs ) ) { $entities = array(); foreach ( $faqs as $faq ) { if ( empty( $faq['question'] ) || empty( $faq['answer'] ) ) { continue; } $entities[] = array( '@type' => 'Question', 'name' => wp_strip_all_tags( (string) $faq['question'] ), 'acceptedAnswer' => array( '@type' => 'Answer', 'text' => wp_strip_all_tags( (string) $faq['answer'] ), ), ); } if ( ! empty( $entities ) ) { $graph[] = array( '@type' => 'FAQPage', '@id' => $url . '#faq', 'mainEntity' => $entities, ); } } /** * Filter the JSON-LD graph before output. * * @param array $graph The graph nodes. * @param WP_Post|null $post The current post, if any. */ return (array) apply_filters( 'airanksuite/schema/graph', $graph, $post ); } /** * Breadcrumb ListItems from the Breadcrumbs module when available. * * @return array> */ private function breadcrumb_items( WP_Post $post, string $home, string $url ): array { $kernel = \AiRankSuite\Kernel::instance(); $trail = array(); if ( class_exists( \AiRankSuite\Modules\Breadcrumbs\BreadcrumbsModule::class ) && in_array( 'breadcrumbs', $kernel->moduleIds(), true ) ) { $module = new \AiRankSuite\Modules\Breadcrumbs\BreadcrumbsModule(); $trail = $module->trail(); } if ( empty( $trail ) ) { $trail = array( array( 'label' => get_bloginfo( 'name' ), 'url' => $home, ), array( 'label' => wp_strip_all_tags( \AiRankSuite\Support\PostSeo::breadcrumb_title( $post ) ), 'url' => $url, ), ); } $items = array(); foreach ( array_values( $trail ) as $index => $item ) { $entry = array( '@type' => 'ListItem', 'position' => $index + 1, 'name' => wp_strip_all_tags( (string) $item['label'] ), ); if ( '' !== (string) $item['url'] ) { $entry['item'] = (string) $item['url']; } $items[] = $entry; } return $items; } public function routes(): void { register_rest_route( self::NAMESPACE, '/settings/schema', array( array( 'methods' => 'GET', 'callback' => array( $this, 'get_settings' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), ), array( 'methods' => 'PUT', 'callback' => array( $this, 'update_settings' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), 'args' => array( 'enabled' => array( 'type' => 'boolean' ), 'org_name' => array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), 'org_type' => array( 'type' => 'string', 'enum' => Services\Identity::type_values(), ), 'force_output' => array( 'type' => 'boolean' ), 'identity' => array( 'type' => 'object' ), ), ), ) ); // The live graph, exactly as it ships — "show me the structured data" // answered without leaving WordPress or opening view-source. register_rest_route( self::NAMESPACE, '/schema/live', array( 'methods' => 'GET', 'callback' => array( $this, 'live_graph' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), ) ); register_rest_route( self::NAMESPACE, '/schema/types', array( 'methods' => 'GET', 'callback' => static fn() => new WP_REST_Response( array( 'types' => Services\SchemaTypes::all(), 'grouped' => Services\SchemaTypes::grouped(), 'variables' => Services\SchemaTypes::variables(), 'usage' => self::usage(), 'featured' => self::featured(), ) ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), ) ); // A post is named in the URL, so the plugin capability is only half the // question: reading needs read_post on that post and writing needs // edit_post. Without it any reports user could pull the schema — title, // FAQ, author — of somebody else's private draft by counting ids. register_rest_route( self::NAMESPACE, '/schema/post/(?P\d+)', array( array( 'methods' => 'GET', 'callback' => array( $this, 'get_post_schema' ), 'permission_callback' => static fn( $request ): bool => current_user_can( 'manage_options' ) && self::post_allowed( (int) ( $request['id'] ?? 0 ), 'read_post' ), ), array( 'methods' => 'PUT', 'callback' => array( $this, 'update_post_schema' ), 'permission_callback' => static fn( $request ): bool => current_user_can( 'manage_options' ) && self::post_allowed( (int) ( $request['id'] ?? 0 ), 'edit_post' ), 'args' => array( 'items' => array( 'type' => 'array', 'required' => true, ), ), ), ) ); register_rest_route( self::NAMESPACE, '/schema/templates', array( array( 'methods' => 'GET', 'callback' => array( $this, 'get_templates' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), ), array( 'methods' => 'PUT', 'callback' => array( $this, 'update_templates' ), 'permission_callback' => static fn(): bool => current_user_can( 'manage_options' ), 'args' => array( 'templates' => array( 'type' => 'array', 'required' => true, ), ), ), ) ); register_rest_route( self::NAMESPACE, '/schema/import', array( 'methods' => 'POST', 'callback' => array( $this, 'import_url' ), 'permission_callback' => static function () { if ( ! current_user_can( 'manage_options' ) ) { return self::forbidden(); } return self::spend( 'schema_import', 30 ); }, 'args' => array( 'url' => array( 'type' => 'string', 'required' => true, ), ), ) ); } /** * How many published pages carry each schema type right now. * * Counted from the per-post items rather than from the rendered graph: * rendering every page to count types would be a crawl, and the answer the * customer wants — "have I actually used Recipe anywhere" — is in the meta. * * @return array */ private static function usage(): array { global $wpdb; // Cached for ten minutes: this runs on every open of the Schema // screen, and the answer moves only when somebody saves an item — // which clears it (see clear_usage_cache()). $cached = get_transient( 'airanksuite_schema_usage' ); if ( is_array( $cached ) ) { return $cached; } $key = Services\SchemaBuilder::META_ITEMS; $out = array(); // Batches by meta_id cursor, so the number of pages that carry items // bounds the number of round trips and never the size of one result // set in memory. A capped single query used to stop counting at // 5,000 rows and report too-low numbers on large sites. $cursor = 0; $batch = 2000; for ( $guard = 0; $guard < 500; $guard++ ) { // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared $rows = $wpdb->get_results( $wpdb->prepare( "SELECT m.meta_id, m.meta_value FROM {$wpdb->postmeta} m INNER JOIN {$wpdb->posts} p ON p.ID = m.post_id WHERE m.meta_key = %s AND p.post_status = 'publish' AND m.meta_id > %d ORDER BY m.meta_id ASC LIMIT %d", $key, $cursor, $batch ) ); // phpcs:enable if ( empty( $rows ) ) { break; } foreach ( $rows as $row ) { $cursor = max( $cursor, (int) $row->meta_id ); $items = maybe_unserialize( $row->meta_value ); if ( is_string( $items ) ) { $items = json_decode( $items, true ); } foreach ( (array) $items as $item ) { $type = (string) ( is_array( $item ) ? ( $item['type'] ?? '' ) : '' ); if ( '' !== $type ) { $out[ $type ] = ( $out[ $type ] ?? 0 ) + 1; } } } if ( count( $rows ) < $batch ) { break; } } // Types the plugin emits automatically, so the screen does not report // "0 pages" for markup that is on every page of the site. $settings = \AiRankSuite\Kernel::service( Options::class )->get( 'schema', self::defaults() ); if ( ! empty( $settings['enabled'] ) ) { $out['__auto'] = 1; } set_transient( 'airanksuite_schema_usage', $out, 10 * MINUTE_IN_SECONDS ); return $out; } /** Forget the cached counts — called whenever per-post items change. */ public static function clear_usage_cache(): void { delete_transient( 'airanksuite_schema_usage' ); } /** * The types worth putting in front of somebody, rather than behind a * search box in a list of 77. * * @return list> */ private static function featured(): array { $has_woo = class_exists( 'WooCommerce' ); $list = array( array( 'type' => 'Article', 'why' => __( 'Blog posts and guides. Carries the author, dates and publisher an assistant needs to attribute a quote.', 'ai-rank-suite' ), 'auto' => true, ), array( 'type' => 'Product', 'why' => __( 'Price, availability, GTIN, brand, shipping and returns — everything Merchant Center demands.', 'ai-rank-suite' ), 'auto' => $has_woo, ), array( 'type' => 'FAQPage', 'why' => __( 'The single most quotable format there is. Generated from any page in the Content panel.', 'ai-rank-suite' ), 'auto' => false, ), array( 'type' => 'Recipe', 'why' => __( 'Times, yield, ingredients and steps, read from WP Recipe Maker when it is installed.', 'ai-rank-suite' ), 'auto' => false, ), array( 'type' => 'HowTo', 'why' => __( 'Step-by-step instructions, with tools and materials. Assistants lift these almost verbatim.', 'ai-rank-suite' ), 'auto' => false, ), array( 'type' => 'LocalBusiness', 'why' => __( 'Address, hours, price range and geo — how a local query resolves to you rather than a competitor.', 'ai-rank-suite' ), 'auto' => false, ), array( 'type' => 'Event', 'why' => __( 'Dates, venue and ticket offers, read from The Events Calendar when it is installed.', 'ai-rank-suite' ), 'auto' => false, ), array( 'type' => 'JobPosting', 'why' => __( 'Salary, location and employment type — the fields Google for Jobs requires.', 'ai-rank-suite' ), 'auto' => false, ), array( 'type' => 'VideoObject', 'why' => __( 'Duration, thumbnail and upload date, so a video can appear as a result in its own right.', 'ai-rank-suite' ), 'auto' => false, ), array( 'type' => 'Course', 'why' => __( 'Provider, duration and mode of study — what a course comparison is built from.', 'ai-rank-suite' ), 'auto' => false, ), array( 'type' => 'Review', 'why' => __( 'A rating with an author and a subject, which is what produces stars in a result.', 'ai-rank-suite' ), 'auto' => false, ), array( 'type' => 'BreadcrumbList', 'why' => __( 'The path shown above a search result instead of a raw URL.', 'ai-rank-suite' ), 'auto' => true, ), ); $types = Services\SchemaTypes::all(); $out = array(); foreach ( $list as $entry ) { $definition = $types[ $entry['type'] ] ?? null; if ( null === $definition ) { continue; } $out[] = array_merge( $entry, array( 'label' => (string) ( $definition['label'] ?? $entry['type'] ), 'fields' => count( (array) ( $definition['fields'] ?? array() ) ), ) ); } return $out; } public function get_settings(): WP_REST_Response { $settings = $this->options()->get( 'schema', self::defaults() ); $identity = array_merge( Services\Identity::defaults(), (array) ( $settings['identity'] ?? array() ) ); return new WP_REST_Response( array( 'settings' => $settings, 'conflict' => SeoModule::conflict(), 'types' => Services\Identity::types(), 'identifiers' => Services\Identity::identifiers(), 'policies' => Services\Identity::policies(), 'contactTypes' => Services\Identity::contact_types(), 'entity' => Services\Identity::completeness( $identity ), 'preview' => Services\Identity::properties( $identity ), ) ); } public function update_settings( WP_REST_Request $request ): WP_REST_Response { $defaults = self::defaults(); $values = array(); foreach ( array_keys( $defaults ) as $key ) { if ( 'identity' === $key || ! $request->has_param( $key ) ) { continue; } $values[ $key ] = $request->get_param( $key ); } if ( $request->has_param( 'identity' ) ) { $values['identity'] = $this->clean_identity( (array) $request->get_param( 'identity' ) ); } $this->options()->set( 'schema', $values, $defaults ); return $this->get_settings(); } /** * Whitelist and clamp the identity payload. * * Free-text lists are the interesting risk here: knowsAbout and sameAs are * rendered into JSON-LD, so both the key set and the item count are fixed * server-side rather than trusted from the form. * * @param array $input Raw payload. * @return array */ private function clean_identity( array $input ): array { $defaults = Services\Identity::defaults(); $out = array(); // The logo is a URL, not prose — it gets URL sanitisation, not text. if ( isset( $input['logo'] ) ) { $out['logo'] = esc_url_raw( (string) $input['logo'] ); } $text = array( 'legal_name', 'alt_name', 'slogan', 'founder', 'employees', 'phone', 'price_range', 'parent_org', 'founded' ); foreach ( $text as $key ) { if ( isset( $input[ $key ] ) ) { $out[ $key ] = mb_substr( sanitize_text_field( (string) $input[ $key ] ), 0, 200 ); } } if ( isset( $input['description'] ) ) { $out['description'] = mb_substr( sanitize_textarea_field( (string) $input['description'] ), 0, 1000 ); } if ( isset( $input['email'] ) ) { $out['email'] = sanitize_email( (string) $input['email'] ); } $lists = array( 'same_as' => 60, 'knows_about' => 60, 'area_served' => 60, 'languages' => 40, 'currencies' => 20, 'payments' => 20, 'awards' => 30, 'certifications' => 30, 'member_of' => 30, ); foreach ( $lists as $key => $cap ) { if ( ! isset( $input[ $key ] ) ) { continue; } $items = array_slice( (array) $input[ $key ], 0, $cap ); $items = array_values( array_filter( array_map( static function ( $item ) use ( $key ): string { $item = trim( (string) $item ); // sameAs is a list of URLs and nothing else. return 'same_as' === $key ? (string) esc_url_raw( $item ) : sanitize_text_field( $item ); }, $items ) ) ); $out[ $key ] = $items; } if ( isset( $input['identifiers'] ) ) { $known = Services\Identity::identifiers(); $clean = array(); foreach ( (array) $input['identifiers'] as $key => $value ) { $key = sanitize_key( (string) $key ); if ( isset( $known[ $key ] ) ) { $clean[ $key ] = mb_substr( sanitize_text_field( (string) $value ), 0, 80 ); } } $out['identifiers'] = $clean; } if ( isset( $input['policies'] ) ) { $known = Services\Identity::policies(); $clean = array(); foreach ( (array) $input['policies'] as $key => $value ) { $key = sanitize_key( (string) $key ); if ( isset( $known[ $key ] ) ) { $clean[ $key ] = esc_url_raw( (string) $value ); } } $out['policies'] = $clean; } if ( isset( $input['contacts'] ) ) { $types = Services\Identity::contact_types(); $clean = array(); foreach ( array_slice( (array) $input['contacts'], 0, 12 ) as $contact ) { if ( ! is_array( $contact ) ) { continue; } $type = (string) ( $contact['type'] ?? 'customer support' ); $clean[] = array( 'type' => isset( $types[ $type ] ) ? $type : 'customer support', 'phone' => mb_substr( sanitize_text_field( (string) ( $contact['phone'] ?? '' ) ), 0, 40 ), 'email' => sanitize_email( (string) ( $contact['email'] ?? '' ) ), 'languages' => array_values( array_filter( array_map( 'sanitize_text_field', array_slice( (array) ( $contact['languages'] ?? array() ), 0, 12 ) ) ) ), 'areas' => array_values( array_filter( array_map( 'sanitize_text_field', array_slice( (array) ( $contact['areas'] ?? array() ), 0, 20 ) ) ) ), ); } $out['contacts'] = $clean; } return array_merge( $defaults, $out ); } /** * Schema items for a post, with validation and a live preview. */ public function get_post_schema( WP_REST_Request $request ): WP_REST_Response|WP_Error { $post = get_post( (int) $request['id'] ); // The route has already asked; asked again because update_post_schema() // and anything else that calls this directly has not. if ( ! $post instanceof WP_Post || ! current_user_can( 'read_post', $post->ID ) ) { return new WP_Error( 'airanksuite_content_not_found', __( 'Post not found.', 'ai-rank-suite' ), array( 'status' => 404 ) ); } $items = Services\SchemaBuilder::items( $post->ID ); $builder = new Services\SchemaBuilder(); $url = (string) get_permalink( $post ); $org = home_url( '/' ) . '#organization'; $preview = array(); $validation = array(); foreach ( $items as $index => $item ) { $node = $builder->build( (string) $item['type'], (array) $item['data'], $post, $url, $org, $index ); if ( null !== $node ) { $preview[] = $node; } $validation[] = Services\SchemaBuilder::validate( (string) $item['type'], (array) $item['data'] ); } $templates = array(); foreach ( Services\SchemaTemplates::matching( $post ) as $template ) { $templates[] = array( 'name' => (string) $template['name'], 'type' => (string) $template['type'], ); } return new WP_REST_Response( array( 'items' => $items, 'types' => Services\SchemaTypes::all(), 'grouped' => Services\SchemaTypes::grouped(), 'variables' => Services\SchemaTypes::variables(), 'preview' => $preview, 'validation' => $validation, 'templates' => $templates, ) ); } public function update_post_schema( WP_REST_Request $request ): WP_REST_Response|WP_Error { $post = get_post( (int) $request['id'] ); if ( ! $post instanceof WP_Post || ! current_user_can( 'edit_post', $post->ID ) ) { return new WP_Error( 'airanksuite_content_not_found', __( 'Post not found.', 'ai-rank-suite' ), array( 'status' => 404 ) ); } Services\SchemaBuilder::save( $post->ID, (array) $request->get_param( 'items' ) ); return $this->get_post_schema( $request ); } public function get_templates(): WP_REST_Response { $taxonomies = array(); $label_use = array(); foreach ( get_taxonomies( array( 'public' => true ), 'objects' ) as $taxonomy ) { $terms = get_terms( array( 'taxonomy' => $taxonomy->name, 'hide_empty' => false, 'number' => 100, ) ); if ( is_wp_error( $terms ) || empty( $terms ) ) { continue; } $label = (string) $taxonomy->labels->singular_name; $label_use[ $label ] = ( $label_use[ $label ] ?? 0 ) + 1; $taxonomies[] = array( 'name' => $label, 'slug' => (string) $taxonomy->name, 'object_types' => array_values( (array) $taxonomy->object_type ), 'terms' => array_map( static fn( $t ) => array( 'id' => (int) $t->term_id, 'name' => (string) $t->name, ), $terms ), ); } // WooCommerce ships a "Category" and a "Tag" of its own, so two groups // in the term picker would carry the same name and the customer could // not tell which one they were choosing. Disambiguate only where the // label actually collides — adding "(post)" to every label would be // noise on the common single-taxonomy site. foreach ( $taxonomies as $i => $taxonomy ) { if ( ( $label_use[ $taxonomy['name'] ] ?? 0 ) > 1 ) { $scope = implode( ', ', $taxonomy['object_types'] ); $taxonomies[ $i ]['name'] = '' !== $scope ? $taxonomy['name'] . ' (' . $scope . ')' : $taxonomy['name'] . ' (' . $taxonomy['slug'] . ')'; } } return new WP_REST_Response( array( 'templates' => Services\SchemaTemplates::all(), 'grouped' => Services\SchemaTypes::grouped(), 'types' => Services\SchemaTypes::all(), 'variables' => Services\SchemaTypes::variables(), 'post_types' => \AiRankSuite\Support\Inventory::eligible_types(), 'taxonomies' => $taxonomies, ) ); } public function update_templates( WP_REST_Request $request ): WP_REST_Response { Services\SchemaTemplates::save( (array) $request->get_param( 'templates' ) ); return $this->get_templates(); } public function import_url( WP_REST_Request $request ): WP_REST_Response|WP_Error { $found = Services\SchemaTemplates::import_from_url( (string) $request->get_param( 'url' ) ); return is_wp_error( $found ) ? $found : new WP_REST_Response( array( 'found' => $found ) ); } private function options(): Options { return \AiRankSuite\Kernel::service( Options::class ); } }