Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.00% covered (success)
95.00%
57 / 60
50.00% covered (danger)
50.00%
2 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
Post_Schema_Node
95.00% covered (success)
95.00%
57 / 60
50.00% covered (danger)
50.00%
2 / 4
22
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%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 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 and post types opted in through the filter.
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        // unless a site opts its own post types in through the filter below.
71        $default = 'post' === $post->post_type ? 'article' : '';
72
73        /**
74         * Filters the Schema type a post gets when no per-post type is set, e.g. to
75         * give a custom post type Article schema by default.
76         *
77         * @since $$next-version$$
78         *
79         * @param string  $default `article`, or '' for none.
80         * @param WP_Post $post    The post.
81         */
82        $type = apply_filters( 'jetpack_seo_default_schema_type', $default, $post );
83
84        return 'article' === $type ? 'article' : '';
85    }
86
87    /**
88     * Article JSON-LD.
89     *
90     * @param WP_Post $post The post.
91     * @return array
92     */
93    private static function build_article( WP_Post $post ) {
94        $node = array(
95            '@type'            => 'Article',
96            'headline'         => \WP_HTML_Decoder::decode_text_node( wp_strip_all_tags( get_the_title( $post ) ) ),
97            'datePublished'    => get_post_time( 'c', true, $post ),
98            'dateModified'     => get_post_modified_time( 'c', true, $post ),
99            'mainEntityOfPage' => array(
100                '@type' => 'WebPage',
101                '@id'   => get_permalink( $post ),
102            ),
103        );
104
105        $image = get_the_post_thumbnail_url( $post, 'full' );
106        if ( $image ) {
107            $node['image'] = $image;
108        }
109
110        $description = Post_Seo::get_description( $post );
111        if ( $description ) {
112            // Cap it: get_description() falls back to full post_content, which
113            // would otherwise dump the whole body into the markup. Decode last, or
114            // wp_trim_words() would strip decoded text such as "<div>".
115            $node['description'] = \WP_HTML_Decoder::decode_text_node( wp_trim_words( wp_strip_all_tags( $description ), self::DESCRIPTION_MAX_WORDS, '' ) );
116        }
117
118        return $node;
119    }
120
121    /**
122     * FAQPage JSON-LD, parsed from `core/details` blocks (summary = question,
123     * rendered content = answer). Returns null when the post has none, so we
124     * never emit an empty/invalid FAQPage.
125     *
126     * @param WP_Post $post The post.
127     * @return array|null
128     */
129    private static function build_faq( WP_Post $post ) {
130        if ( ! function_exists( 'parse_blocks' ) ) {
131            return null;
132        }
133
134        // render_block() skips the `the_content` chain, so the paywall never sees this text.
135        if ( Content_Gate::is_gated( $post ) ) {
136            return null;
137        }
138
139        $items = array();
140        foreach ( parse_blocks( $post->post_content ) as $block ) {
141            if ( 'core/details' !== ( $block['blockName'] ?? '' ) ) {
142                continue;
143            }
144            $question = trim( \WP_HTML_Decoder::decode_text_node( wp_strip_all_tags( (string) ( $block['innerHTML'] ?? '' ) ) ) );
145
146            // Render only the inner blocks for the answer. Rendering the whole
147            // core/details block would re-include the <summary> (the question).
148            $answer_html = '';
149            foreach ( $block['innerBlocks'] ?? array() as $inner_block ) {
150                $answer_html .= render_block( $inner_block );
151            }
152            $answer = trim( \WP_HTML_Decoder::decode_text_node( wp_strip_all_tags( $answer_html ) ) );
153            if ( '' === $question || '' === $answer ) {
154                continue;
155            }
156            $items[] = array(
157                '@type'          => 'Question',
158                'name'           => $question,
159                'acceptedAnswer' => array(
160                    '@type' => 'Answer',
161                    'text'  => $answer,
162                ),
163            );
164        }
165
166        if ( empty( $items ) ) {
167            return null;
168        }
169
170        return array(
171            '@type'      => 'FAQPage',
172            'mainEntity' => $items,
173        );
174    }
175}