build_runtime_fallback_schema( $post_id ); if ( empty( $schema ) ) { return; } update_post_meta( $post_id, self::META_KEY, $schema ); } $json = wp_json_encode( $schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ); if ( ! $json ) { return; } // Printed through the core helper so the tag goes through WordPress' // script-tag filters. $json is already safely encoded for ld+json. wp_print_inline_script_tag( $json, array( 'type' => 'application/ld+json' ) ); } /** * Generate schema for older Ranktim posts imported before JSON-LD meta existed. */ private function build_runtime_fallback_schema( int $post_id ): array { $permalink = get_permalink( $post_id ); if ( ! $permalink ) { return array(); } $description = get_post_meta( $post_id, '_ranktim_meta_description', true ); if ( ! is_string( $description ) || '' === trim( $description ) ) { $description = get_the_excerpt( $post_id ); } $author_id = (int) get_post_field( 'post_author', $post_id ); $author = $author_id > 0 ? get_the_author_meta( 'display_name', $author_id ) : ''; $image = get_the_post_thumbnail_url( $post_id, 'full' ); $keywords = $this->get_runtime_keywords( $post_id ); $schema = array( '@context' => 'https://schema.org', '@type' => 'BlogPosting', 'headline' => wp_strip_all_tags( get_the_title( $post_id ) ), 'author' => array( '@type' => 'Person', 'name' => $author ? $author : get_bloginfo( 'name' ), ), 'publisher' => array( '@type' => 'Organization', 'name' => get_bloginfo( 'name' ), 'url' => home_url( '/' ), ), 'datePublished' => get_post_time( 'c', false, $post_id ), 'dateModified' => get_post_modified_time( 'c', false, $post_id ), 'url' => $permalink, 'mainEntityOfPage' => array( '@type' => 'WebPage', '@id' => $permalink, ), ); if ( is_string( $description ) && '' !== trim( $description ) ) { $schema['description'] = trim( wp_strip_all_tags( $description ) ); } if ( is_string( $image ) && '' !== trim( $image ) ) { $schema['image'] = array( esc_url_raw( $image ) ); } if ( ! empty( $keywords ) ) { $schema['keywords'] = $keywords; } return $schema; } /** * Read Ranktim keyword meta stored during article import. */ private function get_runtime_keywords( int $post_id ): array { $keywords = array(); $primary = get_post_meta( $post_id, '_ranktim_primary_keyword', true ); if ( is_string( $primary ) && '' !== trim( $primary ) ) { $keywords[] = sanitize_text_field( $primary ); } $secondary = get_post_meta( $post_id, '_ranktim_secondary_keywords', true ); if ( is_array( $secondary ) ) { foreach ( $secondary as $keyword ) { if ( is_string( $keyword ) && '' !== trim( $keyword ) ) { $keywords[] = sanitize_text_field( $keyword ); } } } return array_values( array_unique( $keywords ) ); } }