-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson-ld.php
More file actions
487 lines (429 loc) · 16.8 KB
/
Copy pathjson-ld.php
File metadata and controls
487 lines (429 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
<?php
// Full walkthrough: https://marcelbest.com/webdesign/2026/json-ld-fuer-wordpress-ohne-plugin/ (German)
/**
* Connected JSON-LD @graph for classic WordPress themes
*
* Outputs a single JSON-LD @graph in wp_head, with all nodes cross-linked by
* stable @id references (no duplicated, isolated snippets). Emitted nodes by context:
* - WebSite, Person: always
* - BlogPosting: single posts — includes a SpeakableSpecification (headline + lead)
* and, when the post contains an Accordion/FAQ, a linked FAQPage node
* - Blog: front page
* - CollectionPage: category / tag / taxonomy archives
* - WebPage: static pages
* - BreadcrumbList: whenever the breadcrumb has more than one item
*
* No plugin, no build step. Drop into a classic theme and require it from
* functions.php. Everything site-specific (identity, social links, description,
* speakable selectors, FAQ block) is overridable via filters — see the README.
*
* Requires PHP 8.0+ and a classic (non-block) theme.
*/
// Title separator used in CollectionPage / WebPage / Blog names. Override in your theme.
if ( ! defined( 'YOURTHEME_JSONLD_SEPARATOR' ) ) {
define( 'YOURTHEME_JSONLD_SEPARATOR', '|' );
}
/**
* `hentry` is a microformat — the class name itself is the `@type`. Crawlers read
* structured data directly from HTML class attributes, so the only way to stop the
* implicit (and now redundant) hentry markup is to remove the class. Removing it has
* no visual impact; WordPress does not use `hentry` for styling. Disable via the
* `yourtheme_jsonld_remove_hentry` filter if your theme relies on it.
*/
add_filter( 'post_class', function( $classes ) {
if ( apply_filters( 'yourtheme_jsonld_remove_hentry', true ) ) {
return array_diff( $classes, array( 'hentry' ) );
}
return $classes;
} );
/**
* SEO description with a fallback chain:
* 1. Excerpt (singular)
* 2. Term description (category / tag / taxonomy archives)
*
* The result is passed through the `yourtheme_jsonld_description` filter so an SEO
* plugin (Yoast, Essential SEO, …) or your theme can supply or override it.
*/
if ( ! function_exists( 'yourtheme_jsonld_get_description' ) ) :
function yourtheme_jsonld_get_description() {
$description = '';
if ( is_singular() ) {
$excerpt = get_the_excerpt();
if ( $excerpt ) {
$description = $excerpt;
}
} elseif ( is_category() || is_tag() || is_tax() ) {
$term = get_queried_object();
if ( $term && isset( $term->term_id, $term->taxonomy ) ) {
$term_desc = term_description( $term->term_id, $term->taxonomy );
if ( $term_desc ) {
$description = wp_strip_all_tags( $term_desc );
}
}
}
return apply_filters( 'yourtheme_jsonld_description', $description );
}
endif;
/**
* Social profile URLs for the Person node's `sameAs`. Empty by default; provide your
* profiles via the `yourtheme_jsonld_person_social` filter (array of URLs).
*/
if ( ! function_exists( 'yourtheme_jsonld_get_social_links' ) ) :
function yourtheme_jsonld_get_social_links() {
$links = apply_filters( 'yourtheme_jsonld_person_social', array() );
$clean = array();
foreach ( (array) $links as $link ) {
$url = esc_url_raw( $link );
if ( $url ) {
$clean[] = $url;
}
}
return array_values( array_unique( $clean ) );
}
endif;
/**
* Returns breadcrumb items as an array for the BreadcrumbList node.
* Each item has 'name' and 'url' (null for the current page).
*/
if ( ! function_exists( 'yourtheme_jsonld_get_breadcrumb_items' ) ) :
function yourtheme_jsonld_get_breadcrumb_items() {
$items = array();
$items[] = array(
'name' => __( 'Home', 'yourtheme' ),
'url' => get_home_url(),
);
if ( is_single() ) {
$categories = get_the_category();
if ( $categories ) {
$cat = $categories[0];
$items[] = array(
'name' => $cat->name,
'url' => get_category_link( $cat->term_id ),
);
}
$items[] = array(
'name' => get_the_title(),
'url' => null,
);
} elseif ( is_page() && ! is_front_page() ) {
$items[] = array(
'name' => get_the_title(),
'url' => null,
);
} elseif ( is_category() || is_tag() || is_tax() ) {
$term = get_queried_object();
$items[] = array(
'name' => $term->name,
'url' => null,
);
} elseif ( is_search() ) {
$items[] = array(
'name' => sprintf( __( 'Search: %s', 'yourtheme' ), get_search_query() ),
'url' => null,
);
}
return apply_filters( 'yourtheme_jsonld_breadcrumb_items', $items );
}
endif;
/**
* Return a block's name without its namespace (e.g. `core/accordion` -> `accordion`).
*/
if ( ! function_exists( 'yourtheme_jsonld_block_base_name' ) ) :
function yourtheme_jsonld_block_base_name( $block_name ) {
if ( ! is_string( $block_name ) || '' === $block_name ) {
return '';
}
$slash = strrpos( $block_name, '/' );
return false === $slash ? $block_name : substr( $block_name, $slash + 1 );
}
endif;
/**
* Recursively find the first block whose base name (after the namespace) matches.
*/
if ( ! function_exists( 'yourtheme_jsonld_find_block_by_name' ) ) :
function yourtheme_jsonld_find_block_by_name( $blocks, $base_name ) {
foreach ( $blocks as $block ) {
if ( isset( $block['blockName'] ) && yourtheme_jsonld_block_base_name( $block['blockName'] ) === $base_name ) {
return $block;
}
if ( ! empty( $block['innerBlocks'] ) ) {
$found = yourtheme_jsonld_find_block_by_name( $block['innerBlocks'], $base_name );
if ( $found ) {
return $found;
}
}
}
return null;
}
endif;
/**
* Extract FAQ items (question/answer pairs) from a post's Accordion block.
*
* Convention: the Accordion block (core/accordion, WordPress 6.9+) is used exclusively
* for FAQ sections, so its mere presence produces a FAQPage node — no extra authoring markup.
* The block's server-side Core markup is parsed here; any client-side rewrite of the
* accordion (e.g. a Bootstrap port) is irrelevant, since the parser reads the markup
* the server delivers.
*
* The target block (base name) is filterable via `yourtheme_jsonld_faq_block`.
*
* Returns an empty array when no matching block is present or none of its items
* yield a usable question/answer pair.
*/
if ( ! function_exists( 'yourtheme_jsonld_get_faq_items' ) ) :
function yourtheme_jsonld_get_faq_items( $post_id ) {
$post = get_post( $post_id );
if ( ! $post ) {
return array();
}
$block_name = apply_filters( 'yourtheme_jsonld_faq_block', 'accordion' );
$accordion = yourtheme_jsonld_find_block_by_name( parse_blocks( $post->post_content ), $block_name );
if ( ! $accordion ) {
return array();
}
$html = render_block( $accordion );
if ( '' === trim( $html ) ) {
return array();
}
// Parse the rendered Core markup. The XML prolog forces UTF-8; libxml warnings
// about HTML5 elements are expected and silenced.
$dom = new DOMDocument();
libxml_use_internal_errors( true );
$dom->loadHTML( '<?xml encoding="UTF-8" ?>' . $html );
libxml_clear_errors();
$xpath = new DOMXPath( $dom );
$has_class = function ( $class ) {
return "contains(concat(' ', normalize-space(@class), ' '), ' " . $class . " ')";
};
$items = array();
foreach ( $xpath->query( '//*[' . $has_class( 'wp-block-accordion-item' ) . ']' ) as $item ) {
$title = $xpath->query( './/*[' . $has_class( 'wp-block-accordion-heading__toggle-title' ) . ']', $item )->item( 0 );
$panel = $xpath->query( './/*[' . $has_class( 'wp-block-accordion-panel' ) . ']', $item )->item( 0 );
if ( ! $title || ! $panel ) {
continue;
}
// textContent is already entity-decoded; the toggle icon lives in a separate
// span and is therefore not part of the title.
$question = trim( preg_replace( '/\s+/', ' ', $title->textContent ) );
$answer = trim( preg_replace( '/\s+/', ' ', $panel->textContent ) );
if ( '' !== $question && '' !== $answer ) {
$items[] = array(
'question' => $question,
'answer' => $answer,
);
}
}
return $items;
}
endif;
/**
* Build and output the JSON-LD @graph in wp_head.
*/
if ( ! function_exists( 'yourtheme_jsonld_output' ) ) :
function yourtheme_jsonld_output() {
$base_url = get_bloginfo( 'url' );
$site_id = $base_url . '/#website';
// Person / author identity. Defaults are derived from the site; override via filters
// so the file can be reused without editing it.
$person_id = apply_filters( 'yourtheme_jsonld_person_id', $base_url . '/#person' );
$person_name = apply_filters( 'yourtheme_jsonld_person_name', get_bloginfo( 'name' ) );
$person_url = apply_filters( 'yourtheme_jsonld_person_url', $base_url );
$separator = YOURTHEME_JSONLD_SEPARATOR;
$graph = array();
// WebSite
$graph[] = array(
'@type' => 'WebSite',
'@id' => $site_id,
'name' => get_bloginfo( 'name' ),
'description' => get_bloginfo( 'description' ),
'url' => $base_url,
'publisher' => array( '@id' => $person_id ),
);
// Person
$person = array(
'@type' => 'Person',
'@id' => $person_id,
'name' => $person_name,
'url' => $person_url,
);
$social_links = yourtheme_jsonld_get_social_links();
if ( ! empty( $social_links ) ) {
$person['sameAs'] = $social_links;
}
$graph[] = $person;
// Single post
if ( is_single() ) {
// Guard against post_modified predating post_date (e.g. a post saved as
// a draft before being published): dateModified must never be earlier
// than datePublished in the structured data. Compared via 'U' timestamps
// so a DST offset change does not skew the result.
$date_modified = get_the_modified_date( 'c' );
if ( get_the_modified_date( 'U' ) < get_the_date( 'U' ) ) {
$date_modified = get_the_date( 'c' );
}
$block = array(
'@type' => 'BlogPosting',
'@id' => get_permalink() . '#blogposting',
'mainEntityOfPage' => get_permalink(),
'url' => get_permalink(),
'headline' => get_the_title(),
'datePublished' => get_the_date( 'c' ),
'dateModified' => $date_modified,
'inLanguage' => get_bloginfo( 'language' ),
'isPartOf' => array( '@id' => $site_id ),
'author' => array( '@id' => $person_id ),
'publisher' => array( '@id' => $person_id ),
// Marks headline and lead as suitable for text-to-speech (answer engines).
'speakable' => array(
'@type' => 'SpeakableSpecification',
'cssSelector' => apply_filters( 'yourtheme_jsonld_speakable_selectors', array( '.post-header h1', '.post-excerpt' ) ),
),
);
$desc = yourtheme_jsonld_get_description();
if ( $desc ) {
$block['description'] = $desc;
}
// Featured image as the post's primary image (omitted when absent — no empty field).
if ( has_post_thumbnail() ) {
$image_url = get_the_post_thumbnail_url( get_the_ID(), 'large' );
if ( $image_url ) {
$block['image'] = $image_url;
}
}
// Categories as articleSection.
$categories = get_the_category();
if ( $categories ) {
$sections = array();
foreach ( $categories as $category ) {
$sections[] = $category->name;
}
$block['articleSection'] = $sections;
}
// Tags as keywords.
$tags = get_the_tags();
if ( $tags ) {
$keywords = array();
foreach ( $tags as $tag ) {
$keywords[] = $tag->name;
}
$block['keywords'] = $keywords;
}
$graph[] = $block;
// FAQ (from the Accordion block) as a linked FAQPage node.
$faq_items = yourtheme_jsonld_get_faq_items( get_the_ID() );
if ( $faq_items ) {
$questions = array();
foreach ( $faq_items as $faq ) {
$questions[] = array(
'@type' => 'Question',
'name' => $faq['question'],
'acceptedAnswer' => array(
'@type' => 'Answer',
'text' => $faq['answer'],
),
);
}
$graph[] = array(
'@type' => 'FAQPage',
'@id' => get_permalink() . '#faq',
'inLanguage' => get_bloginfo( 'language' ),
'isPartOf' => array( '@id' => $site_id ),
'about' => array( '@id' => get_permalink() . '#blogposting' ),
'mainEntity' => $questions,
);
}
}
// Blog overview (front page)
if ( is_front_page() ) {
// Default to the static posts page if one is set, else the home URL.
$default_blog_url = $base_url;
$posts_page = get_option( 'page_for_posts' );
if ( $posts_page ) {
$permalink = get_permalink( $posts_page );
if ( $permalink ) {
$default_blog_url = $permalink;
}
}
$blog_url = apply_filters( 'yourtheme_jsonld_blog_url', $default_blog_url );
$block = array(
'@type' => 'Blog',
'@id' => $blog_url . '#blog',
'name' => get_bloginfo( 'name' ) . ' ' . $separator . ' ' . get_the_title(),
'url' => $blog_url,
'isPartOf' => array( '@id' => $site_id ),
);
$desc = yourtheme_jsonld_get_description();
if ( $desc ) {
$block['description'] = $desc;
}
$graph[] = $block;
}
// Category and tag archives
if ( is_category() || is_tag() || is_tax() ) {
$term = get_queried_object();
$term_link = get_term_link( $term );
// Skip the CollectionPage node entirely if the term link is unresolvable,
// rather than emit a broken @id/url. The rest of the graph still outputs.
if ( ! is_wp_error( $term_link ) ) {
$block = array(
'@type' => 'CollectionPage',
'@id' => $term_link . '#collectionpage',
'name' => $term->name . ' ' . $separator . ' ' . get_bloginfo( 'name' ),
'url' => $term_link,
'isPartOf' => array( '@id' => $site_id ),
);
$desc = yourtheme_jsonld_get_description();
if ( $desc ) {
$block['description'] = $desc;
}
$graph[] = $block;
}
}
// Static pages
if ( is_page() && ! is_front_page() ) {
$block = array(
'@type' => 'WebPage',
'@id' => get_permalink() . '#webpage',
'name' => get_the_title() . ' ' . $separator . ' ' . get_bloginfo( 'name' ),
'url' => get_permalink(),
'isPartOf' => array( '@id' => $site_id ),
'author' => array( '@id' => $person_id ),
);
$desc = yourtheme_jsonld_get_description();
if ( $desc ) {
$block['description'] = $desc;
}
$graph[] = $block;
}
// BreadcrumbList
$breadcrumb_items = yourtheme_jsonld_get_breadcrumb_items();
if ( count( $breadcrumb_items ) > 1 ) {
$list_items = array();
foreach ( $breadcrumb_items as $position => $item ) {
$list_item = array(
'@type' => 'ListItem',
'position' => $position + 1,
'name' => $item['name'],
);
if ( ! empty( $item['url'] ) ) {
$list_item['item'] = $item['url'];
}
$list_items[] = $list_item;
}
$graph[] = array(
'@type' => 'BreadcrumbList',
'itemListElement' => $list_items,
);
}
// Final escape hatch: filter the whole graph before output.
$graph = apply_filters( 'yourtheme_jsonld_graph', $graph );
$output = array(
'@context' => 'https://schema.org',
'@graph' => $graph,
);
echo '<script type="application/ld+json">'
. wp_json_encode( $output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG )
. '</script>';
}
endif;
add_action( 'wp_head', 'yourtheme_jsonld_output' );