PluginProbe
Parse.ly / 3.8.4
Parse.ly v3.8.4
3.24.1 3.24.0 3.23.7 3.23.6 3.23.5 3.23.4 3.23.3 3.16.0 3.16.1 3.16.2 3.16.3 3.16.4 3.17.0 3.18.0 3.18.1 3.19.0 3.19.1 3.19.2 3.19.3 3.2.0 3.2.1 3.20.0 3.20.1 3.20.2 3.20.3 All 105 releases
wp-parsely / src / Metadata / class-post-builder.php

class-post-builder.php in Parse.ly 3.8.4, at src/Metadata/class-post-builder.php

588 lines 17.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Post Page Metadata Builder class
4 *
5 * @package Parsely
6 * @since 3.4.0
7 */
8
9 declare(strict_types=1);
10
11 namespace Parsely\Metadata;
12
13 use Parsely\Parsely;
14 use WP_Post;
15 use WP_User;
16
17 use function Parsely\Utils\get_default_category;
18
19 /**
20 * Implements abstract Metadata Builder class to generate the metadata array
21 * for a post page.
22 *
23 * @since 3.4.0
24 *
25 * @phpstan-import-type Parsely_Options from Parsely
26 */
27 class Post_Builder extends Metadata_Builder {
28 /**
29 * Post object to generate the metadata for.
30 *
31 * @var WP_Post
32 */
33 private $post;
34
35 /**
36 * Constructor.
37 *
38 * @param Parsely $parsely Instance of Parsely class.
39 * @param WP_Post $post Post object to generate the metadata for.
40 */
41 public function __construct( Parsely $parsely, WP_Post $post ) {
42 parent::__construct( $parsely );
43 $this->post = $post;
44 }
45
46 /**
47 * Generates the metadata object by calling the build_* methods and
48 * returns the value.
49 *
50 * @since 3.4.0
51 *
52 * @return array<string, mixed>
53 */
54 public function get_metadata(): array {
55 $this->build_basic();
56 $this->build_headline();
57 $this->build_url();
58
59 $this->build_type();
60 $this->build_main_entity();
61 $this->build_thumbnail_url();
62 $this->build_image();
63 $this->build_article_section();
64 $this->build_author();
65 $this->build_publisher();
66 $this->build_keywords();
67 $this->build_metadata_post_times();
68
69 return $this->metadata;
70 }
71
72 /**
73 * Populates the `headline` field in the metadata object.
74 *
75 * @since 3.4.0
76 */
77 private function build_headline(): void {
78 $this->metadata['headline'] = $this->clean_value( get_the_title( $this->post ) );
79 }
80
81 /**
82 * Populates the `url` field in the metadata object by getting the current page's URL.
83 *
84 * @since 3.4.0
85 */
86 protected function build_url(): void {
87 $this->metadata['url'] = $this->get_current_url( 'post', $this->post->ID );
88 }
89
90 /**
91 * Populates the `@type` field in the metadata object.
92 *
93 * @since 3.4.0
94 */
95 private function build_type(): void {
96 /**
97 * Filters the JSON-LD @type.
98 *
99 * @param string $jsonld_type JSON-LD @type value, default is NewsArticle.
100 * @param int $id Post ID.
101 * @param string $post_type The Post type in WordPress.
102 *
103 * @since 2.5.0
104 */
105 $type = apply_filters( 'wp_parsely_post_type', 'NewsArticle', $this->post->ID, $this->post->post_type );
106 $supported_types = $this->parsely->get_all_supported_types();
107
108 // Validate type before passing it further as an invalid type will not be recognized by Parse.ly.
109 if ( ! in_array( $type, $supported_types, true ) ) {
110 $error = sprintf(
111 /* translators: 1: JSON @type like NewsArticle, 2: URL */
112 __( '@type %1$s is not supported by Parse.ly. Please use a type mentioned in %2$s', 'wp-parsely' ),
113 $type,
114 'https://www.parse.ly/help/integration/jsonld#distinguishing-between-posts-and-pages'
115 );
116 // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
117 trigger_error( esc_html( $error ), E_USER_WARNING );
118 $type = 'NewsArticle';
119 }
120
121 $this->metadata['@type'] = $type;
122 }
123
124 /**
125 * Populates the `mainEntityOfPage` field in the metadata object.
126 *
127 * @since 3.4.0
128 */
129 private function build_main_entity(): void {
130 $this->metadata['mainEntityOfPage'] = array(
131 '@type' => 'WebPage',
132 '@id' => $this->get_current_url( 'post' ),
133 );
134 }
135
136 /**
137 * Populates the `thumbnailUrl` field in the metadata object.
138 *
139 * @since 3.4.0
140 */
141 private function build_thumbnail_url(): void {
142 $thumb_url = get_the_post_thumbnail_url( $this->post, 'thumbnail' );
143 if ( ! is_string( $thumb_url ) ) {
144 $thumb_url = '';
145 }
146 $this->metadata['thumbnailUrl'] = $thumb_url;
147 }
148
149 /**
150 * Populates the `image` field in the metadata object.
151 *
152 * @since 3.4.0
153 */
154 private function build_image(): void {
155 $image_url = get_the_post_thumbnail_url( $this->post, 'full' );
156 if ( ! is_string( $image_url ) ) {
157 $image_url = '';
158 }
159 $this->metadata['image'] = array(
160 '@type' => 'ImageObject',
161 'url' => $image_url,
162 );
163 }
164
165 /**
166 * Populates the `articleSection` field in the metadata object.
167 *
168 * @since 3.4.0
169 */
170 private function build_article_section(): void {
171 $this->metadata['articleSection'] = $this->get_category_name( $this->post, $this->parsely->get_options() );
172 }
173
174 /**
175 * Populates the `author` and `creator` fields in the metadata object.
176 *
177 * @since 3.4.0
178 */
179 private function build_author(): void {
180 $authors = $this->get_author_names( $this->post );
181 $author_objects = array();
182 foreach ( $authors as $author ) {
183 $author_tag = array(
184 '@type' => 'Person',
185 'name' => $author,
186 );
187 $author_objects[] = $author_tag;
188 }
189 $this->metadata['author'] = $author_objects;
190 $this->metadata['creator'] = $authors;
191 }
192
193 /**
194 * Populates the `publisher` field in the metadata object.
195 *
196 * @since 3.4.0
197 */
198 private function build_publisher(): void {
199 $this->metadata['publisher'] = array(
200 '@type' => 'Organization',
201 'name' => get_bloginfo( 'name' ),
202 'logo' => $this->parsely->get_options()['logo'],
203 );
204 }
205
206 /**
207 * Populates the `keywords` field in the metadata object.
208 *
209 * @since 3.4.0
210 */
211 private function build_keywords(): void {
212 $options = $this->parsely->get_options();
213 $tags = $this->get_tags( $this->post->ID );
214 if ( $options['cats_as_tags'] ) {
215 $tags = array_merge( $tags, $this->get_categories( $this->post->ID ) );
216 // add custom taxonomy values.
217 $tags = array_merge( $tags, $this->get_custom_taxonomy_values( $this->post ) );
218 }
219 // The function 'mb_strtolower' is not enabled by default in php, so this check
220 // falls back to the native php function 'strtolower' if necessary.
221 if ( function_exists( 'mb_strtolower' ) ) {
222 $lowercase_callback = 'mb_strtolower';
223 } else {
224 $lowercase_callback = 'strtolower';
225 }
226 if ( $options['lowercase_tags'] ) {
227 $tags = array_map( $lowercase_callback, $tags );
228 }
229
230 /**
231 * Filters the post tags that are used as metadata keywords.
232 *
233 * @param array<string> $tags Post tags.
234 * @param int $ID Post ID.
235 *
236 * @since 1.8.0
237 */
238 $tags = apply_filters( 'wp_parsely_post_tags', $tags, $this->post->ID );
239 $tags = array_map( array( $this, 'clean_value' ), $tags );
240
241 $this->metadata['keywords'] = array_values( array_unique( $tags ) );
242 }
243
244 /**
245 * Sets all metadata values related to post time.
246 *
247 * @since 3.0.2
248 * @since 3.3.0 Moved to class-metadata
249 */
250 private function build_metadata_post_times(): void {
251 $date_format = 'Y-m-d\TH:i:s\Z';
252 $post_created_gmt = get_post_time( $date_format, true, $this->post );
253
254 if ( false === $post_created_gmt ) {
255 return;
256 }
257
258 $this->metadata['dateCreated'] = $post_created_gmt;
259 $this->metadata['datePublished'] = $post_created_gmt;
260 $this->metadata['dateModified'] = $post_created_gmt;
261
262 $post_modified_gmt = get_post_modified_time( $date_format, true, $this->post );
263
264 if ( false !== $post_modified_gmt && $post_modified_gmt > $post_created_gmt ) {
265 $this->metadata['dateModified'] = $post_modified_gmt;
266 }
267 }
268
269 /**
270 * Returns a properly cleaned category/taxonomy value and will optionally
271 * use the top-level category/taxonomy value, if so instructed via the
272 * `use_top_level_cats` option.
273 *
274 * @since 3.3.0 Moved to class-metadata
275 *
276 * @param WP_Post $post_obj The object for the post.
277 * @param Parsely_Options $parsely_options The parsely options.
278 *
279 * @return string Cleaned category name for the post in question.
280 */
281 private function get_category_name( WP_Post $post_obj, $parsely_options ): string {
282 $taxonomy_dropdown_choice = get_the_terms( $post_obj->ID, $parsely_options['custom_taxonomy_section'] );
283 // Get top-level taxonomy name for chosen taxonomy and assign to $parent_name; it will be used
284 // as the category value if 'use_top_level_cats' option is checked.
285 // Assign as the default category name if no value is checked for the chosen taxonomy.
286 $category_name = get_cat_name( get_default_category() );
287 if ( false !== $taxonomy_dropdown_choice && ! is_wp_error( $taxonomy_dropdown_choice ) ) {
288 if ( $parsely_options['use_top_level_cats'] ) {
289 $first_term = array_shift( $taxonomy_dropdown_choice );
290 if ( null !== $first_term ) {
291 $term_name = $this->get_top_level_term( $first_term->term_id, $first_term->taxonomy );
292 }
293 } else {
294 $term_name = $this->get_bottom_level_term( $post_obj->ID, $parsely_options['custom_taxonomy_section'] );
295 }
296
297 if ( isset( $term_name ) && is_string( $term_name ) && 0 < strlen( $term_name ) ) {
298 $category_name = $term_name;
299 }
300 }
301
302 /**
303 * Filters the constructed category name.
304 *
305 * @since 1.8.0
306 *
307 * @param string $category Category name.
308 * @param WP_Post $post_obj Post object.
309 * @param array<string, mixed> $parsely_options The Parsely options.
310 */
311 $category_name = apply_filters( 'wp_parsely_post_category', $category_name, $post_obj, $parsely_options );
312
313 return $this->clean_value( $category_name );
314 }
315
316 /**
317 * Returns the top-most category/taxonomy value in a hierarchy given a
318 * taxonomy value's ID.
319 *
320 * (WordPress calls taxonomy values 'terms').
321 *
322 * @since 3.3.0 Moved to class-metadata
323 *
324 * @param int $term_id The ID of the top level term.
325 * @param string $taxonomy_name The name of the taxonomy.
326 * @return string|false $parent The top level name of the category / taxonomy.
327 */
328 private function get_top_level_term( int $term_id, string $taxonomy_name ) {
329 $parent = get_term_by( 'id', $term_id, $taxonomy_name );
330
331 while ( false !== $parent && isset( $parent->parent ) && 0 !== $parent->parent ) {
332 $parent = get_term_by( 'id', $parent->parent, $taxonomy_name );
333 }
334
335 return $parent->name ?? false;
336 }
337
338 /**
339 * Returns the bottom-most category/taxonomy value in a hierarchy given a
340 * post ID.
341 *
342 * (WordPress calls taxonomy values 'terms').
343 *
344 * @since 3.3.0 Moved to class-metadata
345 *
346 * @param int $post_id The post id you're interested in.
347 * @param string $taxonomy_name The name of the taxonomy.
348 * @return string Name of the custom taxonomy.
349 */
350 private function get_bottom_level_term( int $post_id, string $taxonomy_name ): string {
351 $terms = get_the_terms( $post_id, $taxonomy_name );
352
353 if ( ! is_array( $terms ) ) {
354 return '';
355 }
356
357 $term_ids = wp_list_pluck( $terms, 'term_id' );
358 $parents = array_filter( wp_list_pluck( $terms, 'parent' ) );
359
360 // Get array of IDs of terms which are not parents.
361 $term_ids_not_parents = array_diff( $term_ids, $parents );
362 // Get corresponding term objects, which are mapped to array index keys.
363 $terms_not_parents = array_intersect_key( $terms, $term_ids_not_parents );
364 // remove array index keys.
365 $terms_not_parents_cleaned = array_values( $terms_not_parents );
366
367 if ( isset( $terms_not_parents_cleaned[0] ) ) {
368 // If you assign multiple child terms in a custom taxonomy, will only return the first.
369 return $terms_not_parents_cleaned[0]->name;
370 }
371
372 return '';
373 }
374
375 /**
376 * Retrieves all the authors for a post as an array. Can include multiple
377 * authors if the Co-Authors Plus plugin is in use.
378 *
379 * @since 3.3.0 Moved to class-metadata
380 *
381 * @param WP_Post $post The post object.
382 * @return array<string>
383 */
384 private function get_author_names( WP_Post $post ): array {
385 $authors = $this->get_coauthor_names( $post->ID );
386 if ( 0 === count( $authors ) ) {
387 $post_author = get_user_by( 'id', $post->post_author );
388 if ( false !== $post_author ) {
389 $authors = array( $post_author );
390 }
391 }
392
393 /**
394 * Filters the list of author WP_User objects for a post.
395 *
396 * @since 1.14.0
397 *
398 * @param array<WP_User> $authors One or more authors as WP_User objects.
399 * @param WP_Post $post Post object.
400 */
401 $authors = apply_filters( 'wp_parsely_pre_authors', $authors, $post );
402
403 // Getting the author name for each author.
404 $authors = array_map( array( $this, 'get_author_name' ), $authors );
405
406 /**
407 * Filters the list of author names for a post.
408 *
409 * @since 1.14.0
410 *
411 * @param array<string> $authors One or more author names.
412 * @param WP_Post $post Post object.
413 */
414 $authors = apply_filters( 'wp_parsely_post_authors', $authors, $post );
415
416 return array_map( array( $this, 'clean_value' ), $authors );
417 }
418
419 /**
420 * Returns a list of coauthors for a post assuming the Co-Authors Plus plugin
421 * is installed.
422 *
423 * Borrowed from
424 * https://github.com/Automattic/Co-Authors-Plus/blob/master/template-tags.php#L3-35
425 *
426 * @since 3.3.0 Moved to class-metadata
427 *
428 * @param int $post_id The ID of the post.
429 * @return array<WP_User> List of coauthors, or an empty array if the Co-Authors Plus plugin is not active.
430 */
431 private function get_coauthor_names( int $post_id ): array {
432 $coauthors = array();
433 if ( class_exists( 'coauthors_plus' ) ) {
434 global $post, $post_ID, $coauthors_plus;
435
436 if ( ! ( $post_id > 0 ) && $post_ID ) {
437 $post_id = $post_ID;
438 }
439
440 if ( ! $post_id && $post ) {
441 $post_id = $post->ID;
442 }
443
444 if ( $post_id ) {
445 $coauthor_terms = get_the_terms( $post_id, $coauthors_plus->coauthor_taxonomy );
446
447 if ( is_array( $coauthor_terms ) ) {
448 foreach ( $coauthor_terms as $coauthor ) {
449 $coauthor_slug = preg_replace( '#^cap-#', '', $coauthor->slug );
450 $post_author = $coauthors_plus->get_coauthor_by( 'user_nicename', $coauthor_slug );
451 // In case the user has been deleted while plugin was deactivated.
452 if ( false !== $post_author ) {
453 $coauthors[] = new WP_User( $post_author );
454 }
455 }
456 } elseif ( ! $coauthors_plus->force_guest_authors ) {
457 if ( $post && $post_id === $post->ID ) {
458 $post_author = get_userdata( $post->post_author );
459 }
460 if ( isset( $post_author ) && false !== $post_author ) {
461 $coauthors[] = $post_author;
462 }
463 }
464 // The empty else case is because if we force guest authors, we don't ever care what value wp_posts.post_author has.
465 }
466 }
467 return $coauthors;
468 }
469
470 /**
471 * Determines author name from display name, falling back to firstname
472 * lastname, then nickname and finally the nicename.
473 *
474 * @since 3.3.0 Moved to class-metadata
475 *
476 * @param ?WP_User $author The author of the post.
477 * @return string An author name.
478 */
479 private function get_author_name( ?WP_User $author ): string {
480 // Gracefully handle situation where no author is available.
481 if ( null === $author ) {
482 return '';
483 }
484
485 if ( '' !== $author->display_name ) {
486 return $author->display_name;
487 }
488
489 $author_name = $author->user_firstname . ' ' . $author->user_lastname;
490 if ( ' ' !== $author_name ) {
491 return $author_name;
492 }
493
494 if ( '' !== $author->nickname ) {
495 return $author->nickname;
496 }
497
498 if ( '' !== $author->user_nicename ) {
499 return $author->user_nicename;
500 }
501
502 return '';
503 }
504
505 /**
506 * Returns the tags associated with this page or post.
507 *
508 * @since 3.3.0 Moved to class-metadata
509 *
510 * @param int $post_id The ID of the post you're trying to get tags for.
511 * @return array<string> The tags of the post represented by the post id.
512 */
513 private function get_tags( int $post_id ): array {
514 /**
515 * Variable.
516 *
517 * @var array<\WP_Term|null>|\WP_Error
518 */
519 $post_tags = wp_get_post_tags( $post_id );
520 $tags = array();
521
522 if ( ! is_wp_error( $post_tags ) ) {
523 foreach ( $post_tags as $wp_tag ) {
524 if ( null !== $wp_tag ) {
525 $tags[] = $wp_tag->name;
526 }
527 }
528 }
529
530 return $tags;
531 }
532
533 /**
534 * Returns an array of all the child categories for the current post.
535 *
536 * @since 3.3.0 Moved to class-metadata
537 *
538 * @param int $post_id The ID of the post you're trying to get categories for.
539 * @param string $delimiter What character will delimit the categories.
540 * @return array<string> All the child categories of the current post.
541 */
542 private function get_categories( int $post_id, string $delimiter = '/' ): array {
543 $tags = array();
544 foreach ( get_the_category( $post_id ) as $category ) {
545 $hierarchy = get_category_parents( $category->term_id, false, $delimiter );
546 if ( ! is_wp_error( $hierarchy ) ) {
547 $tags[] = rtrim( $hierarchy, '/' );
548 }
549 }
550 // Take last element in the hierarchy, a string representing the full parent->child tree,
551 // and split it into individual category names.
552 $last_tag = end( $tags );
553 if ( false !== $last_tag ) {
554 $tags = explode( '/', $last_tag );
555 }
556
557 // Remove default category name from tags if needed.
558 $default_category_name = get_cat_name( get_default_category() );
559 return array_diff( $tags, array( $default_category_name ) );
560 }
561
562 /**
563 * Gets all term names from all custom taxonomies assigned to a post.
564 *
565 * @since 3.3.0 Moved to class-metadata
566 * @since 3.4.0 Moved to class-post-builder
567 *
568 * @param WP_Post $post_obj The post object to find the terms for.
569 * @return array<string> Term names.
570 */
571 private function get_custom_taxonomy_values( WP_Post $post_obj ): array {
572 // Filter out default WordPress taxonomies.
573 $all_taxonomies = array_diff( get_taxonomies(), array( 'post_tag', 'nav_menu', 'author', 'link_category', 'post_format' ) );
574 $all_values = array();
575
576 foreach ( $all_taxonomies as $taxonomy ) {
577 $custom_taxonomy_objects = get_the_terms( $post_obj->ID, $taxonomy );
578 if ( is_array( $custom_taxonomy_objects ) ) {
579 foreach ( $custom_taxonomy_objects as $custom_taxonomy_object ) {
580 $all_values[] = $custom_taxonomy_object->name;
581 }
582 }
583 }
584
585 return $all_values;
586 }
587 }
588