Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.83% covered (success)
94.83%
55 / 58
50.00% covered (danger)
50.00%
2 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
Post_Schema_Node
94.83% covered (success)
94.83%
55 / 58
50.00% covered (danger)
50.00%
2 / 4
21.06
0.00% covered (danger)
0.00%
0 / 1
 build
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
7
 default_schema_for_post
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 build_article
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
3.00
 build_faq
93.10% covered (success)
93.10%
27 / 29
0.00% covered (danger)
0.00%
0 / 1
9.03
1<?php
2/**
3 * Per-post Schema.org node builder.
4 *
5 * Builds the page-level JSON-LD node for the queried singular post: Article (the
6 * default for standard posts) and FAQPage (when the post uses `core/details`
7 * blocks). The type follows the per-post `jetpack_seo_schema_type` override when
8 * set, otherwise a sensible default by post type. Returns an array node or null
9 * when the post should not emit structured data, so the graph can skip it.
10 *
11 * @package automattic/jetpack-seo-package
12 */
13
14namespace Automattic\Jetpack\SEO;
15
16use WP_Post;
17
18/**
19 * Builds the Article / FAQPage node for a single post.
20 */
21class Post_Schema_Node {
22
23    /**
24     * Max words kept for a schema `description`, so a long post body doesn't
25     * dump its full content into the markup.
26     */
27    const DESCRIPTION_MAX_WORDS = 55;
28
29    /**
30     * Build the JSON-LD node for the queried post, or null when none applies.
31     *
32     * @param WP_Post|null $post The queried post.
33     * @return array|null
34     */
35    public static function build( $post ) {
36        if ( ! ( $post instanceof WP_Post ) ) {
37            return null;
38        }
39
40        // Only emit structured data for published content. Previews, drafts, and
41        // private posts are viewable by logged-in users (and may be edge-cached),
42        // so we must not output JSON-LD for anything that isn't publicly published.
43        if ( 'publish' !== $post->post_status ) {
44            return null;
45        }
46
47        $override = Post_Seo::get_schema_type( $post );
48        $type     = '' !== $override ? $override : self::default_schema_for_post( $post );
49
50        switch ( $type ) {
51            case 'faq':
52                return self::build_faq( $post );
53            case 'article':
54                return self::build_article( $post );
55            default:
56                return null;
57        }
58    }
59
60    /**
61     * Default Schema type for a post when the user has not set an override:
62     * Article for standard posts, none for pages, attachments, or custom types.
63     *
64     * @param WP_Post $post The post.
65     * @return string
66     */
67    private static function default_schema_for_post( WP_Post $post ) {
68        // Only standard posts get Article schema by default; everything else
69        // (pages, attachments, custom post types) requires an explicit override.
70        return 'post' === $post->post_type ? 'article' : '';
71    }
72
73    /**
74     * Article JSON-LD.
75     *
76     * @param WP_Post $post The post.
77     * @return array
78     */
79    private static function build_article( WP_Post $post ) {
80        $node = array(
81            '@type'            => 'Article',
82            'headline'         => \WP_HTML_Decoder::decode_text_node( wp_strip_all_tags( get_the_title( $post ) ) ),
83            'datePublished'    => get_post_time( 'c', true, $post ),
84            'dateModified'     => get_post_modified_time( 'c', true, $post ),
85            'mainEntityOfPage' => array(
86                '@type' => 'WebPage',
87                '@id'   => get_permalink( $post ),
88            ),
89        );
90
91        $image = get_the_post_thumbnail_url( $post, 'full' );
92        if ( $image ) {
93            $node['image'] = $image;
94        }
95
96        $description = Post_Seo::get_description( $post );
97        if ( $description ) {
98            // Cap it: get_description() falls back to full post_content, which
99            // would otherwise dump the whole body into the markup. Decode last, or
100            // wp_trim_words() would strip decoded text such as "<div>".
101            $node['description'] = \WP_HTML_Decoder::decode_text_node( wp_trim_words( wp_strip_all_tags( $description ), self::DESCRIPTION_MAX_WORDS, '' ) );
102        }
103
104        return $node;
105    }
106
107    /**
108     * FAQPage JSON-LD, parsed from `core/details` blocks (summary = question,
109     * rendered content = answer). Returns null when the post has none, so we
110     * never emit an empty/invalid FAQPage.
111     *
112     * @param WP_Post $post The post.
113     * @return array|null
114     */
115    private static function build_faq( WP_Post $post ) {
116        if ( ! function_exists( 'parse_blocks' ) ) {
117            return null;
118        }
119
120        // render_block() skips the `the_content` chain, so the paywall never sees this text.
121        if ( Content_Gate::is_gated( $post ) ) {
122            return null;
123        }
124
125        $items = array();
126        foreach ( parse_blocks( $post->post_content ) as $block ) {
127            if ( 'core/details' !== ( $block['blockName'] ?? '' ) ) {
128                continue;
129            }
130            $question = trim( \WP_HTML_Decoder::decode_text_node( wp_strip_all_tags( (string) ( $block['innerHTML'] ?? '' ) ) ) );
131
132            // Render only the inner blocks for the answer. Rendering the whole
133            // core/details block would re-include the <summary> (the question).
134            $answer_html = '';
135            foreach ( $block['innerBlocks'] ?? array() as $inner_block ) {
136                $answer_html .= render_block( $inner_block );
137            }
138            $answer = trim( \WP_HTML_Decoder::decode_text_node( wp_strip_all_tags( $answer_html ) ) );
139            if ( '' === $question || '' === $answer ) {
140                continue;
141            }
142            $items[] = array(
143                '@type'          => 'Question',
144                'name'           => $question,
145                'acceptedAnswer' => array(
146                    '@type' => 'Answer',
147                    'text'  => $answer,
148                ),
149            );
150        }
151
152        if ( empty( $items ) ) {
153            return null;
154        }
155
156        return array(
157            '@type'      => 'FAQPage',
158            'mainEntity' => $items,
159        );
160    }
161}