PluginProbe
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO / 1.25.0
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO v1.25.0
2.7.0 2.6.0 2.5.0 2.4.0 2.3.0 2.2.0 2.1.1 2.1.0 2.0.2 2.0.1 2.0.0 1.32.0 1.31.0 1.30.0 1.29.0 1.28.0 1.27.0 1.26.0 1.25.0 trunk 1.0.0 1.0.1 1.0.2 1.1.0 1.10.0 All 48 releases
thinkrank / includes / seo / class-social-meta-manager.php

class-social-meta-manager.php in ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO 1.25.0, at includes/seo/class-social-meta-manager.php

2,631 lines 102.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Social Meta Manager Class
4 *
5 * Universal social media meta tag generation and optimization for all platforms.
6 * Implements 2025 social media SEO best practices with real Open Graph and Twitter Card
7 * specifications, social image optimization, and platform-specific handling.
8 *
9 * @package ThinkRank
10 * @subpackage SEO
11 * @since 1.0.0
12 */
13
14 declare(strict_types=1);
15
16 namespace ThinkRank\SEO;
17
18 // Prevent direct access
19 if (!defined('ABSPATH')) {
20 exit;
21 }
22
23 /**
24 * Social Meta Manager Class
25 *
26 * Generates and validates social media meta tags for all supported platforms.
27 * Provides context-aware social meta generation with image optimization and
28 * platform-specific meta tag handling.
29 *
30 * @since 1.0.0
31 */
32 class Social_Meta_Manager extends Abstract_SEO_Manager {
33
34 /**
35 * Supported social media platforms with their specifications
36 *
37 * @since 1.0.0
38 * @var array
39 */
40 private array $supported_platforms = [
41 'facebook' => [
42 'og_required' => ['og:title', 'og:type', 'og:image', 'og:url'],
43 'og_recommended' => ['og:description', 'og:site_name', 'og:locale'],
44 'og_optional' => ['og:updated_time', 'og:see_also', 'og:video', 'og:audio'],
45 'image_min_width' => 600,
46 'image_min_height' => 315,
47 'image_recommended_ratio' => 1.91,
48 'title_max_length' => 60,
49 'description_max_length' => 160
50 ],
51 'twitter' => [
52 'card_types' => ['summary', 'summary_large_image', 'app', 'player'],
53 'required' => ['twitter:card', 'twitter:title'],
54 'recommended' => ['twitter:description', 'twitter:image', 'twitter:site'],
55 'optional' => ['twitter:creator', 'twitter:player', 'twitter:app:name'],
56 'image_min_width' => 300,
57 'image_min_height' => 157,
58 'image_max_size' => 5242880, // 5MB
59 'title_max_length' => 70,
60 'description_max_length' => 200
61 ],
62 'linkedin' => [
63 'og_required' => ['og:title', 'og:type', 'og:image', 'og:url'],
64 'og_recommended' => ['og:description'],
65 'image_min_width' => 1200,
66 'image_min_height' => 627,
67 'image_recommended_ratio' => 1.91,
68 'title_max_length' => 70,
69 'description_max_length' => 160
70 ],
71 'pinterest' => [
72 'required' => ['og:title', 'og:type', 'og:image', 'og:url'],
73 'recommended' => ['og:description', 'og:site_name'],
74 'image_min_width' => 600,
75 'image_min_height' => 900,
76 'image_recommended_ratio' => 0.67, // 2:3 ratio
77 'title_max_length' => 100,
78 'description_max_length' => 500
79 ],
80 'whatsapp' => [
81 'og_required' => ['og:title', 'og:type', 'og:image', 'og:url'],
82 'og_recommended' => ['og:description'],
83 'image_min_width' => 300,
84 'image_min_height' => 200,
85 'title_max_length' => 65,
86 'description_max_length' => 160
87 ]
88 ];
89
90 /**
91 * Open Graph types with their specifications
92 *
93 * @since 1.0.0
94 * @var array
95 */
96 private array $og_types = [
97 'website' => ['og:title', 'og:type', 'og:image', 'og:url'],
98 'article' => ['og:title', 'og:type', 'og:image', 'og:url', 'article:author', 'article:published_time'],
99 'product' => ['og:title', 'og:type', 'og:image', 'og:url', 'product:price:amount', 'product:price:currency'],
100 'video' => ['og:title', 'og:type', 'og:image', 'og:url', 'og:video', 'video:duration'],
101 'music' => ['og:title', 'og:type', 'og:image', 'og:url', 'music:duration', 'music:album'],
102 'book' => ['og:title', 'og:type', 'og:image', 'og:url', 'book:author', 'book:isbn'],
103 'profile' => ['og:title', 'og:type', 'og:image', 'og:url', 'profile:first_name', 'profile:last_name']
104 ];
105
106 /**
107 * Constructor
108 *
109 * @since 1.0.0
110 */
111 public function __construct() {
112 parent::__construct('social_meta');
113 }
114
115 /**
116 * Generate Open Graph tags for content
117 *
118 * @since 1.0.0
119 *
120 * @param array $data Content data for OG generation
121 * @param string $context Context type ('site', 'post', 'page', etc.)
122 * @param string $platform Target platform ('facebook', 'linkedin', etc.)
123 * @return array Generated Open Graph tags
124 */
125 public function generate_og_tags(array $data, string $context = 'site', string $platform = 'facebook'): array {
126 $platform = strtolower($platform);
127 if (!isset($this->supported_platforms[$platform])) {
128 $platform = 'facebook'; // Default fallback
129 }
130
131 $platform_spec = $this->supported_platforms[$platform];
132 $og_tags = [];
133
134 // Determine OG type based on context
135 $og_type = $this->determine_og_type($context, $data);
136 $og_tags['og:type'] = $og_type;
137
138 // Required OG tags
139 // og:title must render the full resolved Open Graph title. The 60-char
140 // cap in optimize_title_for_platform() is an SEO-title recommendation for
141 // search results and does not apply to the og:title social tag, so use the
142 // resolved title verbatim (falling back to the site name when empty).
143 $og_tags['og:title'] = ($data['title'] ?? '') !== '' ? $data['title'] : get_bloginfo('name');
144 $og_tags['og:url'] = $data['url'] ?? $this->get_current_url();
145
146 // Image handling with optimization
147 if (!empty($data['image'])) {
148 $optimized_image = $this->optimize_image_for_platform($data['image'], $platform);
149 $og_tags['og:image'] = $optimized_image['url'];
150 // Emit og:image:secure_url for https images (parity with the basic
151 // emitter), so crawlers that prefer the secure URL get it.
152 if (!empty($optimized_image['url']) && strpos((string) $optimized_image['url'], 'https://') === 0) {
153 $og_tags['og:image:secure_url'] = $optimized_image['url'];
154 }
155 if (!empty($optimized_image['width'])) {
156 $og_tags['og:image:width'] = $optimized_image['width'];
157 }
158 if (!empty($optimized_image['height'])) {
159 $og_tags['og:image:height'] = $optimized_image['height'];
160 }
161 if (!empty($optimized_image['type'])) {
162 $og_tags['og:image:type'] = $optimized_image['type'];
163 }
164 if (!empty($optimized_image['alt'])) {
165 $og_tags['og:image:alt'] = $optimized_image['alt'];
166 }
167 } else {
168 // Fallback to site default image
169 $default_image = $this->get_default_social_image();
170 if ($default_image) {
171 $og_tags['og:image'] = $default_image;
172 }
173 }
174
175 // Recommended OG tags
176 if (!empty($data['description'])) {
177 $og_tags['og:description'] = $this->optimize_description_for_platform($data['description'], $platform);
178 }
179
180 $og_tags['og:site_name'] = $data['site_name'] ?? get_bloginfo('name');
181 $og_tags['og:locale'] = $data['locale'] ?? $this->get_og_locale();
182
183 // Context-specific OG tags
184 $og_tags = $this->add_context_specific_og_tags($og_tags, $context, $data, $og_type);
185
186 // Platform-specific optimizations
187 $og_tags = $this->apply_platform_specific_optimizations($og_tags, $platform, $data);
188
189 return $og_tags;
190 }
191
192 /**
193 * Generate Twitter Card tags for content
194 *
195 * @since 1.0.0
196 *
197 * @param array $data Content data for Twitter Card generation
198 * @param string $context Context type ('site', 'post', 'page', etc.)
199 * @return array Generated Twitter Card tags
200 */
201 public function generate_twitter_tags(array $data, string $context = 'site'): array {
202 $twitter_tags = [];
203
204 // Determine card type based on content
205 $card_type = $this->determine_twitter_card_type($data, $context);
206 $twitter_tags['twitter:card'] = $card_type;
207
208 // Required tags. Prefer a per-post Twitter-specific title, falling back
209 // to the resolved og:title/SEO title. Render it in full — the length cap
210 // in optimize_title_for_platform() is an SEO-title recommendation for
211 // search results, not a rule for the twitter:title social tag.
212 $twitter_title = ($data['twitter_title'] ?? '') !== '' ? $data['twitter_title'] : ($data['title'] ?? '');
213 $twitter_tags['twitter:title'] = $twitter_title !== '' ? $twitter_title : get_bloginfo('name');
214
215 // Recommended tags
216 if (!empty($data['description'])) {
217 $twitter_tags['twitter:description'] = $this->optimize_description_for_platform($data['description'], 'twitter');
218 }
219
220 // Image handling - prioritize Twitter-specific image
221 $twitter_image = !empty($data['twitter_image']) ? $data['twitter_image'] : $data['image'];
222 if (!empty($twitter_image)) {
223 $optimized_image = $this->optimize_image_for_platform($twitter_image, 'twitter');
224 $twitter_tags['twitter:image'] = $optimized_image['url'];
225 if (!empty($optimized_image['alt'])) {
226 $twitter_tags['twitter:image:alt'] = $optimized_image['alt'];
227 }
228 }
229
230 // Site and creator information
231 $twitter_site = $this->get_twitter_site_handle();
232 if ($twitter_site) {
233 $twitter_tags['twitter:site'] = $twitter_site;
234 }
235
236 $twitter_creator = $this->get_twitter_creator_handle();
237 if ($twitter_creator) {
238 $twitter_tags['twitter:creator'] = $twitter_creator;
239 } elseif (!empty($data['author']['twitter'])) {
240 // Fallback to author data if available
241 $twitter_tags['twitter:creator'] = $data['author']['twitter'];
242 }
243
244 // Card-specific tags
245 $twitter_tags = $this->add_twitter_card_specific_tags($twitter_tags, $card_type, $data, $context);
246
247 return $twitter_tags;
248 }
249
250 /**
251 * Optimize social image for platform requirements
252 *
253 * @since 1.0.0
254 *
255 * @param string $image_url Image URL to optimize
256 * @param string $platform Target platform
257 * @return array Optimized image data
258 */
259 public function optimize_social_image(string $image_url, string $platform): array {
260 return $this->optimize_image_for_platform($image_url, $platform);
261 }
262
263 /**
264 * Generate social media preview data
265 *
266 * @since 1.0.0
267 *
268 * @param array $data Content data
269 * @param string $platform Target platform
270 * @return array Preview data for the platform
271 */
272 public function preview_social_post(array $data, string $platform): array {
273 $preview = [
274 'platform' => $platform,
275 'valid' => false,
276 'preview_url' => '',
277 'title' => '',
278 'description' => '',
279 'image' => '',
280 'warnings' => [],
281 'suggestions' => []
282 ];
283
284 switch ($platform) {
285 case 'facebook':
286 case 'linkedin':
287 $og_tags = $this->generate_og_tags($data, 'post', $platform);
288 $preview = $this->generate_og_preview($og_tags, $platform, $preview);
289 break;
290 case 'twitter':
291 $twitter_tags = $this->generate_twitter_tags($data, 'post');
292 $preview = $this->generate_twitter_preview($twitter_tags, $preview);
293 break;
294 case 'pinterest':
295 $og_tags = $this->generate_og_tags($data, 'post', $platform);
296 $preview = $this->generate_pinterest_preview($og_tags, $preview);
297 break;
298 default:
299 $preview['warnings'][] = 'Unsupported platform for preview generation';
300 }
301
302 return $preview;
303 }
304
305 /**
306 * Validate SEO settings (implements interface)
307 *
308 * @since 1.0.0
309 *
310 * @param array $settings Settings array to validate
311 * @param string $context Optional context for focused validation
312 * @return array Validation results
313 */
314 public function validate_settings(array $settings, string $context = 'all'): array {
315 $validation = [
316 'valid' => true,
317 'errors' => [],
318 'warnings' => [],
319 'suggestions' => [],
320 'score' => 100
321 ];
322
323 // Add detailed field validation breakdown
324 $field_details = $this->get_detailed_field_validation($settings, $context);
325 $validation['field_details'] = $field_details;
326
327 // Convert field details to validation format
328 foreach ($field_details as $field) {
329 switch ($field['status']) {
330 case 'error':
331 $validation['errors'][] = $field['label'];
332 $validation['valid'] = false;
333 $validation['score'] -= 15;
334 break;
335 case 'warning':
336 $validation['warnings'][] = $field['label'];
337 $validation['score'] -= 8;
338 break;
339 case 'suggestion':
340 $validation['suggestions'][] = $field['label'];
341 $validation['score'] -= 3;
342 break;
343 }
344 }
345
346 // Ensure score doesn't go below 0
347 $validation['score'] = max(0, $validation['score']);
348
349
350 // Validate general enabled setting (Social Media tab format)
351 if (isset($settings['enabled'])) {
352 // Convert string booleans to actual booleans
353 if (is_string($settings['enabled'])) {
354 $settings['enabled'] = filter_var($settings['enabled'], FILTER_VALIDATE_BOOLEAN);
355 }
356 if (!is_bool($settings['enabled'])) {
357 $validation['errors'][] = 'enabled must be a boolean value';
358 $validation['valid'] = false;
359 }
360 }
361
362 // Validate Open Graph settings (Social Media tab format)
363 if (isset($settings['enable_open_graph'])) {
364 // Convert string booleans to actual booleans
365 if (is_string($settings['enable_open_graph'])) {
366 $settings['enable_open_graph'] = filter_var($settings['enable_open_graph'], FILTER_VALIDATE_BOOLEAN);
367 }
368 if (!is_bool($settings['enable_open_graph'])) {
369 $validation['errors'][] = 'enable_open_graph must be a boolean value';
370 $validation['valid'] = false;
371 }
372 }
373
374 // Validate Twitter Cards settings (Social Media tab format)
375 if (isset($settings['enable_twitter_cards'])) {
376 // Convert string booleans to actual booleans
377 if (is_string($settings['enable_twitter_cards'])) {
378 $settings['enable_twitter_cards'] = filter_var($settings['enable_twitter_cards'], FILTER_VALIDATE_BOOLEAN);
379 }
380 if (!is_bool($settings['enable_twitter_cards'])) {
381 $validation['errors'][] = 'enable_twitter_cards must be a boolean value';
382 $validation['valid'] = false;
383 }
384 }
385
386 // Validate Twitter settings (only when relevant)
387 if ($context === 'all' || $context === 'twitter' || $context === 'twitter-cards') {
388 // Validate Twitter username format
389 if (isset($settings['twitter_username']) && !empty($settings['twitter_username'])) {
390 $username = trim($settings['twitter_username']);
391
392 // Remove @ if present (we store without @, add @ in output)
393 $clean_username = ltrim($username, '@');
394
395 if (empty($clean_username)) {
396 $validation['errors'][] = 'twitter_username cannot be empty';
397 $validation['valid'] = false;
398 } elseif (strlen($clean_username) > 15) {
399 $validation['errors'][] = 'twitter_username must be 15 characters or less';
400 $validation['valid'] = false;
401 } elseif (!preg_match('/^[A-Za-z0-9_]+$/', $clean_username)) {
402 $validation['errors'][] = 'twitter_username can only contain letters, numbers, and underscores';
403 $validation['valid'] = false;
404 }
405
406 // Update the setting to store without @ for consistency
407 $settings['twitter_username'] = $clean_username;
408 }
409
410 // Validate Twitter creator format
411 if (isset($settings['twitter_creator']) && !empty($settings['twitter_creator'])) {
412 $creator = trim($settings['twitter_creator']);
413
414 // Remove @ if present (we store without @, add @ in output)
415 $clean_creator = ltrim($creator, '@');
416
417 if (empty($clean_creator)) {
418 $validation['errors'][] = 'twitter_creator cannot be empty';
419 $validation['valid'] = false;
420 } elseif (strlen($clean_creator) > 15) {
421 $validation['errors'][] = 'twitter_creator must be 15 characters or less';
422 $validation['valid'] = false;
423 } elseif (!preg_match('/^[A-Za-z0-9_]+$/', $clean_creator)) {
424 $validation['errors'][] = 'twitter_creator can only contain letters, numbers, and underscores';
425 $validation['valid'] = false;
426 }
427
428 // Update the setting to store without @ for consistency
429 $settings['twitter_creator'] = $clean_creator;
430 }
431
432 // Validate Twitter card type
433 if (isset($settings['twitter_card_type'])) {
434 $valid_types = ['summary', 'summary_large_image', 'app', 'player'];
435 if (!in_array($settings['twitter_card_type'], $valid_types, true)) {
436 $validation['errors'][] = 'twitter_card_type must be one of: ' . implode(', ', $valid_types);
437 $validation['valid'] = false;
438 }
439 }
440 }
441
442 // Validate OG type
443 if (isset($settings['og_type'])) {
444 $valid_types = ['website', 'article', 'book', 'profile', 'music.song', 'music.album', 'video.movie', 'video.episode'];
445 if (!in_array($settings['og_type'], $valid_types, true)) {
446 $validation['warnings'][] = 'og_type should be one of the standard Open Graph types for best compatibility';
447 }
448 }
449
450 // Validate image dimensions
451 if (isset($settings['og_image_width']) && (!is_numeric($settings['og_image_width']) || $settings['og_image_width'] < 200)) {
452 $validation['warnings'][] = 'og_image_width should be at least 200 pixels for optimal social sharing';
453 }
454
455 if (isset($settings['og_image_height']) && (!is_numeric($settings['og_image_height']) || $settings['og_image_height'] < 200)) {
456 $validation['warnings'][] = 'og_image_height should be at least 200 pixels for optimal social sharing';
457 }
458
459 // Validate description length
460 if (isset($settings['max_description_length']) && (!is_numeric($settings['max_description_length']) || $settings['max_description_length'] < 50 || $settings['max_description_length'] > 300)) {
461 $validation['warnings'][] = 'max_description_length should be between 50 and 300 characters';
462 }
463
464 // Legacy validation for backward compatibility (only when legacy fields are actually present)
465 if (isset($settings['og_enabled'])) {
466 // Convert string booleans to actual booleans
467 if (is_string($settings['og_enabled'])) {
468 $settings['og_enabled'] = filter_var($settings['og_enabled'], FILTER_VALIDATE_BOOLEAN);
469 }
470 if (!is_bool($settings['og_enabled'])) {
471 $validation['errors'][] = 'og_enabled must be a boolean value';
472 $validation['valid'] = false;
473 }
474 }
475
476 if (isset($settings['twitter_enabled'])) {
477 // Convert string booleans to actual booleans
478 if (is_string($settings['twitter_enabled'])) {
479 $settings['twitter_enabled'] = filter_var($settings['twitter_enabled'], FILTER_VALIDATE_BOOLEAN);
480 }
481 if (!is_bool($settings['twitter_enabled'])) {
482 $validation['errors'][] = 'twitter_enabled must be a boolean value';
483 $validation['valid'] = false;
484 }
485 }
486
487 // Validate Twitter card type
488 if (isset($settings['twitter_card_type'])) {
489 $valid_card_types = $this->supported_platforms['twitter']['card_types'];
490 if (!in_array($settings['twitter_card_type'], $valid_card_types, true)) {
491 $validation['errors'][] = 'Invalid Twitter card type. Must be one of: ' . implode(', ', $valid_card_types);
492 $validation['valid'] = false;
493 }
494 }
495
496 // Validate default image
497 if (isset($settings['default_image']) && !empty($settings['default_image'])) {
498 if (!filter_var($settings['default_image'], FILTER_VALIDATE_URL)) {
499 $validation['errors'][] = 'default_image must be a valid URL';
500 $validation['valid'] = false;
501 } else {
502 // Check image dimensions and format
503 $image_validation = $this->validate_social_image($settings['default_image']);
504 if (!$image_validation['valid']) {
505 $validation['warnings'] = array_merge($validation['warnings'], $image_validation['warnings']);
506 }
507 }
508 }
509
510 // Validate Twitter site handle
511 if (isset($settings['twitter_site']) && !empty($settings['twitter_site'])) {
512 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}$/', $settings['twitter_site'])) {
513 $validation['errors'][] = 'twitter_site must be a valid Twitter handle (e.g., @username)';
514 $validation['valid'] = false;
515 }
516 }
517
518 // Validate custom OG tags
519 if (isset($settings['custom_og_tags']) && !empty($settings['custom_og_tags'])) {
520 if (!is_array($settings['custom_og_tags'])) {
521 $validation['errors'][] = 'custom_og_tags must be an array';
522 $validation['valid'] = false;
523 } else {
524 foreach ($settings['custom_og_tags'] as $property => $content) {
525 if (!is_string($property) || !is_string($content)) {
526 $validation['errors'][] = 'Custom OG tags must have string property names and content';
527 $validation['valid'] = false;
528 break;
529 }
530 }
531 }
532 }
533
534 // Validate platform verification codes / IDs (Instagram, TikTok, YouTube,
535 // WhatsApp, Facebook App ID, Pinterest) against the shared format rules.
536 // Single source of truth — also enforced on the Social Platforms REST save
537 // path via self::validate_platform_field(). See get_platform_field_validation_rules().
538 foreach (self::get_platform_field_validation_rules() as $field_key => $rule) {
539 if (isset($settings[$field_key]) && $settings[$field_key] !== '') {
540 $error = self::validate_platform_field($field_key, $settings[$field_key]);
541 if ($error !== null) {
542 $validation['errors'][] = $error;
543 $validation['valid'] = false;
544 }
545 }
546 }
547
548 return $validation;
549 }
550
551 /**
552 * Format-validation rules for social platform verification codes / IDs.
553 *
554 * Single source of truth for the per-field format constraints, shared by
555 * validate_settings() and the Social Platforms REST endpoint
556 * (ThinkRank\API\Social_Platforms_Endpoint) so a value that is accepted on
557 * one path is accepted on the other. These mirror the `pattern` entries in
558 * get_settings_schema(); sanitization strips unsafe characters but does not
559 * enforce shape, so these rules back it with real validation.
560 *
561 * @since 1.14.0
562 *
563 * @return array<string, array{pattern: string, message: string}> Map of field key => rule.
564 */
565 public static function get_platform_field_validation_rules(): array {
566 return [
567 'facebook_app_id' => [
568 'pattern' => '/^[0-9]+$/',
569 'message' => 'Facebook App ID must contain digits only.',
570 ],
571 'pinterest_site_verification' => [
572 'pattern' => '/^[a-f0-9]{32}$/',
573 'message' => 'Pinterest site verification must be a 32-character hexadecimal string.',
574 ],
575 'instagram_verification' => [
576 'pattern' => '/^[a-zA-Z0-9_-]{20,}$/',
577 'message' => 'Instagram verification must be at least 20 characters (letters, numbers, underscore, dash).',
578 ],
579 'tiktok_verification' => [
580 'pattern' => '/^[a-zA-Z0-9_-]{20,}$/',
581 'message' => 'TikTok verification must be at least 20 characters (letters, numbers, underscore, dash).',
582 ],
583 'youtube_channel_id' => [
584 'pattern' => '/^UC[a-zA-Z0-9_-]{22}$/',
585 'message' => 'YouTube channel ID must start with "UC" followed by 22 characters (letters, numbers, underscore, dash).',
586 ],
587 'whatsapp_business_id' => [
588 'pattern' => '/^[0-9]{10,15}$/',
589 'message' => 'WhatsApp Business ID must be 10-15 digits.',
590 ],
591 ];
592 }
593
594 /**
595 * Validate a single social platform field value against its shared format rule.
596 *
597 * Returns null for fields with no format rule (e.g. facebook_admins) and for
598 * empty values, so callers can validate an arbitrary settings map and only
599 * act on genuine format violations.
600 *
601 * @since 1.14.0
602 *
603 * @param string $key Field key.
604 * @param mixed $value Field value.
605 * @return string|null Error message when the value violates the format, null otherwise.
606 */
607 public static function validate_platform_field(string $key, $value): ?string {
608 $rules = self::get_platform_field_validation_rules();
609
610 if (!isset($rules[$key]) || $value === '' || $value === null) {
611 return null;
612 }
613
614 if (!preg_match($rules[$key]['pattern'], (string) $value)) {
615 return $rules[$key]['message'];
616 }
617
618 return null;
619 }
620
621 /**
622 * Get detailed field validation breakdown
623 *
624 * @since 1.0.0
625 *
626 * @param array $settings Settings array to validate
627 * @param string $context Context for specific validation
628 * @return array Detailed field validation results
629 */
630 private function get_detailed_field_validation(array $settings, string $context = 'all'): array {
631 $field_details = [];
632
633 // Return tab-specific validation based on context
634 switch ($context) {
635 case 'open-graph':
636 return $this->validate_open_graph_fields($settings);
637 case 'twitter-cards':
638 return $this->validate_twitter_fields($settings);
639 default:
640 // For 'all' or unknown context, return only Social Media fields (Open Graph + Twitter)
641 $field_details = array_merge($field_details, $this->validate_open_graph_fields($settings));
642 $field_details = array_merge($field_details, $this->validate_twitter_fields($settings));
643 return $field_details;
644 }
645 }
646
647 /**
648 * Validate Open Graph fields
649 *
650 * @since 1.0.0
651 *
652 * @param array $settings Settings array to validate
653 * @return array Open Graph field validation results
654 */
655 private function validate_open_graph_fields(array $settings): array {
656 $field_details = [];
657
658 // Open Graph Enabled
659 if (!empty($settings['enable_open_graph'])) {
660 $field_details[] = [
661 'field' => 'enable_open_graph',
662 'label' => 'Open Graph is enabled for social media sharing.',
663 'status' => 'valid',
664 'icon' => ''
665 ];
666
667 // Site Name validation
668 if (!empty($settings['og_site_name'])) {
669 if (strlen($settings['og_site_name']) <= 60) {
670 $field_details[] = [
671 'field' => 'og_site_name',
672 'label' => 'Site name is properly configured for Open Graph.',
673 'status' => 'valid',
674 'icon' => ''
675 ];
676 } else {
677 $field_details[] = [
678 'field' => 'og_site_name',
679 'label' => 'Site name is longer than 60 characters, may be truncated.',
680 'status' => 'warning',
681 'icon' => ''
682 ];
683 }
684 } else {
685 $field_details[] = [
686 'field' => 'og_site_name',
687 'label' => 'Site name is required for Open Graph.',
688 'status' => 'error',
689 'icon' => ''
690 ];
691 }
692
693 // Description validation
694 if (!empty($settings['og_description'])) {
695 $length = strlen($settings['og_description']);
696 if ($length >= 120 && $length <= 160) {
697 $field_details[] = [
698 'field' => 'og_description',
699 'label' => 'Description is properly configured for social sharing.',
700 'status' => 'valid',
701 'icon' => ''
702 ];
703 } else {
704 $field_details[] = [
705 'field' => 'og_description',
706 'label' => 'Description length could be optimized (120-160 characters recommended).',
707 'status' => 'warning',
708 'icon' => ''
709 ];
710 }
711 } else {
712 $field_details[] = [
713 'field' => 'og_description',
714 'label' => 'Description is recommended for better social sharing.',
715 'status' => 'warning',
716 'icon' => ''
717 ];
718 }
719
720 // Content Type validation
721 if (!empty($settings['og_type'])) {
722 $field_details[] = [
723 'field' => 'og_type',
724 'label' => 'Content type is configured for Open Graph.',
725 'status' => 'valid',
726 'icon' => ''
727 ];
728 } else {
729 $field_details[] = [
730 'field' => 'og_type',
731 'label' => 'Content type should be specified.',
732 'status' => 'suggestion',
733 'icon' => ''
734 ];
735 }
736
737 // Default Image validation
738 if (!empty($settings['default_og_image'])) {
739 if (filter_var($settings['default_og_image'], FILTER_VALIDATE_URL)) {
740 $field_details[] = [
741 'field' => 'default_og_image',
742 'label' => 'Default Open Graph image is configured.',
743 'status' => 'valid',
744 'icon' => ''
745 ];
746 } else {
747 $field_details[] = [
748 'field' => 'default_og_image',
749 'label' => 'Default Open Graph image URL appears invalid.',
750 'status' => 'warning',
751 'icon' => ''
752 ];
753 }
754 } else {
755 $field_details[] = [
756 'field' => 'default_og_image',
757 'label' => 'Default image is recommended for social sharing.',
758 'status' => 'suggestion',
759 'icon' => ''
760 ];
761 }
762
763 } else {
764 $field_details[] = [
765 'field' => 'enable_open_graph',
766 'label' => 'Open Graph is disabled. Enable for better social media sharing.',
767 'status' => 'suggestion',
768 'icon' => ''
769 ];
770 }
771
772 return $field_details;
773 }
774
775 /**
776 * Validate Twitter fields
777 *
778 * @since 1.0.0
779 *
780 * @param array $settings Settings array to validate
781 * @return array Twitter field validation results
782 */
783 private function validate_twitter_fields(array $settings): array {
784 $field_details = [];
785
786 // Twitter Cards Enabled
787 if (!empty($settings['enable_twitter_cards'])) {
788 $field_details[] = [
789 'field' => 'enable_twitter_cards',
790 'label' => 'Twitter Cards are enabled for Twitter sharing.',
791 'status' => 'valid',
792 'icon' => ''
793 ];
794
795 // Twitter Username validation
796 if (!empty($settings['twitter_username'])) {
797 $username = trim($settings['twitter_username']);
798 $clean_username = ltrim($username, '@');
799
800 if (strlen($clean_username) <= 15 && preg_match('/^[A-Za-z0-9_]+$/', $clean_username)) {
801 $field_details[] = [
802 'field' => 'twitter_username',
803 'label' => 'Twitter username is properly formatted.',
804 'status' => 'valid',
805 'icon' => ''
806 ];
807 } else {
808 $field_details[] = [
809 'field' => 'twitter_username',
810 'label' => 'Twitter username format is invalid (max 15 chars, letters/numbers/underscore only).',
811 'status' => 'error',
812 'icon' => ''
813 ];
814 }
815 } else {
816 $field_details[] = [
817 'field' => 'twitter_username',
818 'label' => 'Twitter username recommended for better attribution.',
819 'status' => 'suggestion',
820 'icon' => ''
821 ];
822 }
823
824 // Twitter Creator validation
825 if (!empty($settings['twitter_creator'])) {
826 $creator = trim($settings['twitter_creator']);
827 $clean_creator = ltrim($creator, '@');
828
829 if (strlen($clean_creator) <= 15 && preg_match('/^[A-Za-z0-9_]+$/', $clean_creator)) {
830 $field_details[] = [
831 'field' => 'twitter_creator',
832 'label' => 'Twitter creator is properly formatted.',
833 'status' => 'valid',
834 'icon' => ''
835 ];
836 } else {
837 $field_details[] = [
838 'field' => 'twitter_creator',
839 'label' => 'Twitter creator format is invalid (max 15 chars, letters/numbers/underscore only).',
840 'status' => 'error',
841 'icon' => ''
842 ];
843 }
844 } else {
845 $field_details[] = [
846 'field' => 'twitter_creator',
847 'label' => 'Twitter creator recommended for content attribution.',
848 'status' => 'suggestion',
849 'icon' => ''
850 ];
851 }
852
853 // Card Type validation
854 $valid_card_types = ['summary', 'summary_large_image', 'app', 'player'];
855 if (!empty($settings['twitter_card_type']) && in_array($settings['twitter_card_type'], $valid_card_types)) {
856 $field_details[] = [
857 'field' => 'twitter_card_type',
858 'label' => 'Twitter Card type is properly configured.',
859 'status' => 'valid',
860 'icon' => ''
861 ];
862 } else {
863 $field_details[] = [
864 'field' => 'twitter_card_type',
865 'label' => 'Valid Twitter Card type is required.',
866 'status' => 'error',
867 'icon' => ''
868 ];
869 }
870
871 // Default Twitter Image validation
872 if (!empty($settings['default_twitter_image'])) {
873 if (filter_var($settings['default_twitter_image'], FILTER_VALIDATE_URL)) {
874 $field_details[] = [
875 'field' => 'default_twitter_image',
876 'label' => 'Default Twitter Card image is configured.',
877 'status' => 'valid',
878 'icon' => ''
879 ];
880 } else {
881 $field_details[] = [
882 'field' => 'default_twitter_image',
883 'label' => 'Default Twitter Card image URL appears invalid.',
884 'status' => 'warning',
885 'icon' => ''
886 ];
887 }
888 } else {
889 $field_details[] = [
890 'field' => 'default_twitter_image',
891 'label' => 'Default image recommended for Twitter sharing.',
892 'status' => 'suggestion',
893 'icon' => ''
894 ];
895 }
896
897 } else {
898 $field_details[] = [
899 'field' => 'enable_twitter_cards',
900 'label' => 'Twitter Cards are disabled. Enable for better Twitter sharing.',
901 'status' => 'suggestion',
902 'icon' => ''
903 ];
904 }
905
906 return $field_details;
907 }
908
909
910 /**
911 * Get output data for frontend rendering (implements interface)
912 *
913 * @since 1.0.0
914 *
915 * @param string $context_type The context type
916 * @param int|null $context_id Optional. Context ID
917 * @param string|null $fallback_title Optional. Effective SEO title to
918 * use when no per-post Open Graph
919 * title override is set, so
920 * rendered output mirrors the
921 * document title and the Social
922 * metabox preview.
923 * @param string|null $fallback_description Optional. Effective meta
924 * description, used as the
925 * Open Graph description fallback
926 * for the same parity reason.
927 * @return array Output data ready for frontend rendering
928 */
929 public function get_output_data(string $context_type, ?int $context_id, ?string $fallback_title = null, ?string $fallback_description = null): array {
930 // Memoize per request: the OG, Twitter and platform wp_head callbacks
931 // each call this with the same arguments, so the extraction work +
932 // Site_Identity_Manager instantiation would otherwise run three times.
933 $cache_key = $context_type . ':' . ($context_id ?? 0) . ':' . md5((string) $fallback_title . '|' . (string) $fallback_description);
934 if (isset($this->output_data_cache[$cache_key])) {
935 return $this->output_data_cache[$cache_key];
936 }
937
938 $settings = $this->get_settings($context_type, $context_id);
939 $output = [
940 'og_tags' => [],
941 'twitter_tags' => [],
942 'meta_tags' => [],
943 'platform_tags' => [],
944 // Per-feature flags so each emitter can honor its own toggle. The
945 // aggregate `enabled` (true if either is on) is kept for callers
946 // that only care whether social output ran at all.
947 'og_enabled' => false,
948 'twitter_enabled' => false,
949 'enabled' => false,
950 ];
951
952 // Check if individual social features are enabled
953 $og_enabled = !empty($settings['enable_open_graph'] ?? $settings['og_enabled'] ?? false);
954 $twitter_enabled = !empty($settings['enable_twitter_cards'] ?? $settings['twitter_enabled'] ?? false);
955 $output['og_enabled'] = $og_enabled;
956 $output['twitter_enabled'] = $twitter_enabled;
957
958 if (!$og_enabled && !$twitter_enabled) {
959 $this->output_data_cache[$cache_key] = $output;
960 return $output;
961 }
962
963 $output['enabled'] = true;
964
965 // Extract content data
966 $content_data = $this->extract_social_content_data($context_type, $context_id, $settings, $fallback_title, $fallback_description);
967
968 // Generate Open Graph tags if enabled
969 if ($og_enabled) {
970 $output['og_tags'] = $this->generate_og_tags($content_data, $context_type);
971
972 // Add custom OG tags
973 if (!empty($settings['custom_og_tags'])) {
974 $output['og_tags'] = array_merge($output['og_tags'], $settings['custom_og_tags']);
975 }
976 }
977
978 // Generate Twitter Card tags if enabled
979 if ($twitter_enabled) {
980 $output['twitter_tags'] = $this->generate_twitter_tags($content_data, $context_type);
981 }
982
983 // Generate platform-specific meta tags
984 $output['platform_tags'] = $this->generate_platform_meta_tags($settings);
985
986 // Convert to meta tag format for HTML output
987 $output['meta_tags'] = $this->convert_to_meta_tags($output['og_tags'], $output['twitter_tags'], $output['platform_tags']);
988
989 $this->output_data_cache[$cache_key] = $output;
990 return $output;
991 }
992
993 /**
994 * Request-scoped memoization of get_output_data() keyed by context + title/desc.
995 *
996 * @var array<string, array>
997 */
998 private array $output_data_cache = [];
999
1000 /**
1001 * Site-wide default image keys inherited by every other context.
1002 *
1003 * @since 1.24.1
1004 * @var string[]
1005 */
1006 private const INHERITED_SITE_KEYS = [
1007 'default_og_image',
1008 'default_twitter_image',
1009 'default_image',
1010 ];
1011
1012 /**
1013 * Get settings for a context, inheriting the site-wide default images
1014 *
1015 * Two corrections over the generic lookup:
1016 *
1017 * 1. Site-wide settings are always stored with context_id 0, but the
1018 * frontend maps a homepage request to the `site` context while still
1019 * passing the queried object ID (non-zero on a static front page). That
1020 * looked up `site`/<page ID>, matched no row and silently fell back to
1021 * the schema defaults, so a configured default OG image never rendered
1022 * on a static front page. Normalize the ID away for `site`.
1023 * 2. `default_og_image` / `default_twitter_image` only exist in the site
1024 * context, so post/page and archive contexts had nothing to fall back to
1025 * when a post had no featured image — og:image dropped to the site logo
1026 * or vanished entirely. Inherit those keys when the context has no value
1027 * of its own.
1028 *
1029 * @since 1.24.1
1030 *
1031 * @param string $context_type The context type
1032 * @param int|null $context_id Optional. Context ID
1033 * @return array Settings with site-wide image defaults applied
1034 */
1035 public function get_settings(string $context_type, ?int $context_id = null): array {
1036 if ($context_type === 'site') {
1037 $context_id = null;
1038 }
1039
1040 $settings = parent::get_settings($context_type, $context_id);
1041
1042 if ($context_type === 'site') {
1043 return $settings;
1044 }
1045
1046 $site_settings = parent::get_settings('site', null);
1047 foreach (self::INHERITED_SITE_KEYS as $key) {
1048 if (empty($settings[$key]) && !empty($site_settings[$key])) {
1049 $settings[$key] = $site_settings[$key];
1050 }
1051 }
1052
1053 return $settings;
1054 }
1055
1056 /**
1057 * Get default settings for a context type (implements interface)
1058 *
1059 * @since 1.0.0
1060 *
1061 * @param string $context_type The context type to get defaults for
1062 * @return array Default settings array
1063 */
1064 public function get_default_settings(string $context_type): array {
1065 // Get WordPress site defaults
1066 $site_name = get_bloginfo('name');
1067 $site_description = get_bloginfo('description');
1068
1069 $defaults = [
1070 // Open Graph settings
1071 'enable_open_graph' => true,
1072 'og_site_name' => $site_name,
1073 'og_description' => $site_description,
1074 'og_type' => 'website',
1075 'og_locale' => 'en_US',
1076 'default_og_image' => '',
1077 'og_image_width' => 1200,
1078 'og_image_height' => 630,
1079
1080 // Twitter Cards settings
1081 'enable_twitter_cards' => true,
1082 'twitter_username' => '',
1083 'twitter_creator' => '',
1084 'twitter_card_type' => 'summary_large_image',
1085 'default_twitter_image' => '',
1086
1087 // Facebook settings
1088 'facebook_app_id' => '',
1089 'facebook_admins' => '',
1090
1091 // LinkedIn settings
1092 'enable_linkedin' => false,
1093
1094 // Pinterest settings
1095 'enable_pinterest' => false,
1096 'pinterest_site_verification' => '',
1097
1098 // Instagram settings
1099 'enable_instagram' => false,
1100 'instagram_verification' => '',
1101
1102 // TikTok settings
1103 'enable_tiktok' => false,
1104 'tiktok_verification' => '',
1105
1106 // YouTube settings
1107 'enable_youtube' => false,
1108 'youtube_channel_id' => '',
1109
1110 // WhatsApp Business settings
1111 'enable_whatsapp' => false,
1112 'whatsapp_business_id' => '',
1113
1114 // Advanced settings
1115 'auto_generate_descriptions' => true,
1116 'fallback_to_excerpt' => true,
1117 'strip_html_tags' => true,
1118 'max_description_length' => 160,
1119
1120 // Legacy format for backward compatibility (only when needed)
1121 'custom_og_tags' => [],
1122 'image_optimization' => true,
1123 'auto_generate' => true
1124 ];
1125
1126 // Context-specific defaults
1127 switch ($context_type) {
1128 case 'site':
1129 $defaults['og_type'] = 'website';
1130 break;
1131 case 'post':
1132 $defaults['og_type'] = 'article';
1133 break;
1134 case 'page':
1135 $defaults['og_type'] = 'website';
1136 break;
1137 case 'product':
1138 $defaults['og_type'] = 'product';
1139 break;
1140 }
1141
1142 return $defaults;
1143 }
1144
1145 /**
1146 * Get settings schema definition (implements interface)
1147 *
1148 * @since 1.0.0
1149 *
1150 * @param string $context_type The context type to get schema for
1151 * @return array Settings schema definition
1152 */
1153 public function get_settings_schema(string $context_type): array {
1154 return [
1155 'enable_open_graph' => [
1156 'type' => 'boolean',
1157 'title' => 'Enable Open Graph',
1158 'description' => 'Generate Open Graph meta tags for social media sharing',
1159 'default' => true
1160 ],
1161 'og_site_name' => [
1162 'type' => 'string',
1163 'title' => 'Site Name',
1164 'description' => 'The name of your website for Open Graph',
1165 'maxLength' => 60,
1166 'default' => get_bloginfo('name')
1167 ],
1168 'og_description' => [
1169 'type' => 'string',
1170 'title' => 'Site Description',
1171 'description' => 'Default description for Open Graph tags',
1172 'maxLength' => 160,
1173 'default' => get_bloginfo('description')
1174 ],
1175 'og_type' => [
1176 'type' => 'string',
1177 'title' => 'Open Graph Type',
1178 'description' => 'The type of content for Open Graph',
1179 'enum' => ['website', 'article', 'book', 'profile'],
1180 'default' => 'website'
1181 ],
1182 'og_locale' => [
1183 'type' => 'string',
1184 'title' => 'Locale',
1185 'description' => 'The locale for Open Graph tags',
1186 'default' => 'en_US'
1187 ],
1188 'default_og_image' => [
1189 'type' => 'string',
1190 'title' => 'Default Open Graph Image',
1191 'description' => 'Default image URL for Open Graph tags',
1192 'format' => 'uri',
1193 'default' => ''
1194 ],
1195 'og_image_width' => [
1196 'type' => 'integer',
1197 'title' => 'Image Width',
1198 'description' => 'Default width for Open Graph images',
1199 'minimum' => 200,
1200 'default' => 1200
1201 ],
1202 'og_image_height' => [
1203 'type' => 'integer',
1204 'title' => 'Image Height',
1205 'description' => 'Default height for Open Graph images',
1206 'minimum' => 200,
1207 'default' => 630
1208 ],
1209 'enable_twitter_cards' => [
1210 'type' => 'boolean',
1211 'title' => 'Enable Twitter Cards',
1212 'description' => 'Generate Twitter Card meta tags for Twitter sharing',
1213 'default' => true
1214 ],
1215 'twitter_username' => [
1216 'type' => 'string',
1217 'title' => 'Twitter Username',
1218 'description' => 'Twitter username for the site (without @, e.g., username)',
1219 'pattern' => '^[a-zA-Z0-9_]{1,15}$',
1220 'default' => ''
1221 ],
1222 'twitter_creator' => [
1223 'type' => 'string',
1224 'title' => 'Twitter Creator',
1225 'description' => 'Content creator Twitter username (without @, e.g., creator_username)',
1226 'pattern' => '^[a-zA-Z0-9_]{1,15}$',
1227 'default' => ''
1228 ],
1229 'twitter_card_type' => [
1230 'type' => 'string',
1231 'title' => 'Twitter Card Type',
1232 'description' => 'The type of Twitter Card to generate',
1233 'enum' => $this->supported_platforms['twitter']['card_types'],
1234 'default' => 'summary_large_image'
1235 ],
1236 'og_type' => [
1237 'type' => 'string',
1238 'title' => 'Open Graph Type',
1239 'description' => 'The Open Graph type for this content',
1240 'enum' => array_keys($this->og_types),
1241 'default' => $this->get_default_settings($context_type)['og_type']
1242 ],
1243 'default_image' => [
1244 'type' => 'string',
1245 'title' => 'Default Social Image',
1246 'description' => 'Default image URL for social media sharing',
1247 'format' => 'uri',
1248 'default' => ''
1249 ],
1250 'twitter_site' => [
1251 'type' => 'string',
1252 'title' => 'Twitter Site Handle',
1253 'description' => 'Twitter handle for the site (e.g., @username)',
1254 'pattern' => '^@[a-zA-Z0-9_]{1,15}$',
1255 'default' => ''
1256 ],
1257 'default_twitter_image' => [
1258 'type' => 'string',
1259 'title' => 'Default Twitter Image',
1260 'description' => 'Default image URL for Twitter Cards',
1261 'format' => 'uri',
1262 'default' => ''
1263 ],
1264 'facebook_app_id' => [
1265 'type' => 'string',
1266 'title' => 'Facebook App ID',
1267 'description' => 'Facebook App ID for analytics and insights',
1268 'pattern' => '^[0-9]+$',
1269 'default' => ''
1270 ],
1271 'facebook_admins' => [
1272 'type' => 'string',
1273 'title' => 'Facebook Admins',
1274 'description' => 'Comma-separated list of Facebook admin user IDs',
1275 'default' => ''
1276 ],
1277 'enable_linkedin' => [
1278 'type' => 'boolean',
1279 'title' => 'Enable LinkedIn',
1280 'description' => 'Enable LinkedIn-specific optimizations',
1281 'default' => false
1282 ],
1283 'enable_pinterest' => [
1284 'type' => 'boolean',
1285 'title' => 'Enable Pinterest',
1286 'description' => 'Enable Pinterest-specific optimizations',
1287 'default' => false
1288 ],
1289 'pinterest_site_verification' => [
1290 'type' => 'string',
1291 'title' => 'Pinterest Site Verification',
1292 'description' => 'Pinterest site verification meta tag content',
1293 'pattern' => '^[a-f0-9]{32}$',
1294 'default' => ''
1295 ],
1296 'enable_instagram' => [
1297 'type' => 'boolean',
1298 'title' => 'Enable Instagram',
1299 'description' => 'Enable Instagram-specific optimizations',
1300 'default' => false
1301 ],
1302 'instagram_verification' => [
1303 'type' => 'string',
1304 'title' => 'Instagram Site Verification',
1305 'description' => 'Instagram Business account verification code',
1306 'pattern' => '^[a-zA-Z0-9_-]{20,}$',
1307 'default' => ''
1308 ],
1309 'enable_tiktok' => [
1310 'type' => 'boolean',
1311 'title' => 'Enable TikTok',
1312 'description' => 'Enable TikTok-specific optimizations',
1313 'default' => false
1314 ],
1315 'tiktok_verification' => [
1316 'type' => 'string',
1317 'title' => 'TikTok Site Verification',
1318 'description' => 'TikTok for Business verification code',
1319 'pattern' => '^[a-zA-Z0-9_-]{20,}$',
1320 'default' => ''
1321 ],
1322 'enable_youtube' => [
1323 'type' => 'boolean',
1324 'title' => 'Enable YouTube',
1325 'description' => 'Enable YouTube-specific optimizations',
1326 'default' => false
1327 ],
1328 'youtube_channel_id' => [
1329 'type' => 'string',
1330 'title' => 'YouTube Channel ID',
1331 'description' => 'YouTube channel ID for content attribution',
1332 'pattern' => '^UC[a-zA-Z0-9_-]{22}$',
1333 'default' => ''
1334 ],
1335 'enable_whatsapp' => [
1336 'type' => 'boolean',
1337 'title' => 'Enable WhatsApp Business',
1338 'description' => 'Enable WhatsApp Business optimizations',
1339 'default' => false
1340 ],
1341 'whatsapp_business_id' => [
1342 'type' => 'string',
1343 'title' => 'WhatsApp Business ID',
1344 'description' => 'WhatsApp Business account ID',
1345 'pattern' => '^[0-9]{10,15}$',
1346 'default' => ''
1347 ],
1348 'auto_generate_descriptions' => [
1349 'type' => 'boolean',
1350 'title' => 'Auto-generate Descriptions',
1351 'description' => 'Automatically generate descriptions from content',
1352 'default' => true
1353 ],
1354 'fallback_to_excerpt' => [
1355 'type' => 'boolean',
1356 'title' => 'Fallback to Excerpt',
1357 'description' => 'Use post excerpt as fallback for descriptions',
1358 'default' => true
1359 ],
1360 'strip_html_tags' => [
1361 'type' => 'boolean',
1362 'title' => 'Strip HTML Tags',
1363 'description' => 'Remove HTML tags from generated descriptions',
1364 'default' => true
1365 ],
1366 'max_description_length' => [
1367 'type' => 'integer',
1368 'title' => 'Max Description Length',
1369 'description' => 'Maximum length for generated descriptions',
1370 'minimum' => 50,
1371 'maximum' => 300,
1372 'default' => 160
1373 ],
1374 'custom_og_tags' => [
1375 'type' => 'object',
1376 'title' => 'Custom Open Graph Tags',
1377 'description' => 'Additional custom Open Graph meta tags',
1378 'default' => []
1379 ],
1380 'image_optimization' => [
1381 'type' => 'boolean',
1382 'title' => 'Enable Image Optimization',
1383 'description' => 'Optimize images for social media platforms',
1384 'default' => true
1385 ],
1386 'auto_generate' => [
1387 'type' => 'boolean',
1388 'title' => 'Auto-generate Tags',
1389 'description' => 'Automatically generate social meta tags from content',
1390 'default' => true
1391 ]
1392 ];
1393 }
1394
1395 /**
1396 * Extract content data for social meta generation
1397 *
1398 * @since 1.0.0
1399 *
1400 * @param string $context_type The context type
1401 * @param int|null $context_id Optional. Context ID
1402 * @param array $settings Social meta settings
1403 * @return array Extracted content data
1404 */
1405 private function extract_social_content_data(string $context_type, ?int $context_id, array $settings, ?string $fallback_title = null, ?string $fallback_description = null): array {
1406 $data = [
1407 'title' => '',
1408 'description' => '',
1409 'url' => '',
1410 'image' => '',
1411 'twitter_title' => '', // Separate field for a Twitter-specific title
1412 'twitter_image' => '', // Separate field for Twitter-specific images
1413 'type' => 'website',
1414 'author' => [],
1415 'published_time' => '',
1416 'modified_time' => '',
1417 'site_name' => $settings['og_site_name'] ?? get_bloginfo('name')
1418 ];
1419
1420 if ($context_type === 'site') {
1421 // Site-wide data with Social Media tab settings priority.
1422 //
1423 // og:title priority: an explicitly-configured OG Site Name wins;
1424 // otherwise mirror the effective SEO <title> (what search shows),
1425 // then the blogname. og_site_name is always present because it is
1426 // merged from a default equal to the blogname, so a value matching
1427 // the blogname is treated as "not explicitly overridden" and we fall
1428 // through to the passed effective SEO title. (og:site_name itself is
1429 // set separately from og_site_name and is unaffected.)
1430 $blogname = get_bloginfo('name');
1431 $og_site_name = $settings['og_site_name'] ?? '';
1432 if ($og_site_name !== '' && $og_site_name !== $blogname) {
1433 $data['title'] = $og_site_name;
1434 } elseif ($fallback_title !== null && $fallback_title !== '') {
1435 $data['title'] = $fallback_title;
1436 } else {
1437 $data['title'] = $blogname;
1438 }
1439 $data['description'] = $settings['og_description'] ?? get_bloginfo('description');
1440 // Use home_url('/') so og:url matches the homepage canonical
1441 // (class-seo-manager.php) and the WebSite schema, which both include
1442 // the trailing slash. A bare home_url() would key a different URL in
1443 // social caches than the canonical.
1444 $data['url'] = home_url('/');
1445 $data['type'] = $settings['og_type'] ?? 'website';
1446 $data['locale'] = $settings['og_locale'] ?? null;
1447
1448 // Set Open Graph image with proper fallback
1449 $data['image'] = $this->get_og_image_for_context($settings, null);
1450
1451 // Set Twitter image with proper fallback
1452 $data['twitter_image'] = $this->get_twitter_image_for_context($settings, null);
1453 } elseif ($context_id && in_array($context_type, ['post', 'page', 'product'], true)) {
1454 // Post-specific data
1455 $post = get_post($context_id);
1456 if ($post) {
1457 // Per-post Open Graph overrides from the metabox Social tab take
1458 // precedence over the derived title/description/image. These read
1459 // the same meta keys the metabox save handler and the import
1460 // migrator write to, so manual edits and migrated data flow
1461 // through one path. Title/description may hold variable tags
1462 // (e.g. %title%), resolved here to match output_basic_og_tags().
1463 $og_title_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value(
1464 (string) get_post_meta($post->ID, '_thinkrank_og_title', true),
1465 $post->ID
1466 );
1467 $og_description_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value(
1468 (string) get_post_meta($post->ID, '_thinkrank_og_description', true),
1469 $post->ID
1470 );
1471 $og_image_override = get_post_meta($post->ID, '_thinkrank_og_image', true);
1472
1473 // Per-post Twitter-specific title override (metabox Social tab).
1474 // Twitter Cards fall back to the og:title when this is empty, so
1475 // only capture it here; the fallback is applied in
1476 // generate_twitter_tags().
1477 $data['twitter_title'] = \ThinkRank\SEO\Pattern_Resolver::resolve_value(
1478 (string) get_post_meta($post->ID, '_thinkrank_twitter_title', true),
1479 $post->ID
1480 );
1481
1482 // Title priority: per-post OG override > effective SEO title
1483 // (document <title> / metabox preview) > post title.
1484 if ($og_title_override !== '') {
1485 $data['title'] = $og_title_override;
1486 } elseif ($fallback_title !== null && $fallback_title !== '') {
1487 $data['title'] = $fallback_title;
1488 } else {
1489 $data['title'] = get_the_title($post);
1490 }
1491 // Description priority: per-post OG override > effective meta
1492 // description (meta tag / metabox preview) > derived excerpt.
1493 if ($og_description_override !== '') {
1494 $data['description'] = $og_description_override;
1495 } elseif ($fallback_description !== null && $fallback_description !== '') {
1496 $data['description'] = $fallback_description;
1497 } else {
1498 $data['description'] = $this->get_social_description($post);
1499 }
1500 $data['url'] = get_permalink($post);
1501 $data['type'] = $settings['og_type'] ?? $this->determine_og_type($context_type, []);
1502 $data['published_time'] = get_the_date('c', $post);
1503 $data['modified_time'] = get_the_modified_date('c', $post);
1504 $data['post_id'] = $post->ID;
1505
1506 // Author data
1507 $author_id = $post->post_author;
1508 $data['author'] = [
1509 'name' => get_the_author_meta('display_name', $author_id),
1510 'url' => get_author_posts_url($author_id),
1511 'twitter' => get_the_author_meta('twitter', $author_id)
1512 ];
1513
1514 // Set Open Graph image: per-post override first, then the
1515 // featured-image/default fallback chain.
1516 $data['image'] = $og_image_override !== ''
1517 ? $og_image_override
1518 : $this->get_og_image_for_context($settings, $post);
1519
1520 // Set Twitter image with proper fallback
1521 $data['twitter_image'] = $this->get_twitter_image_for_context($settings, $post);
1522 }
1523 } else {
1524 // Archive-style contexts (category, tag, author, search, date).
1525 // They carry no object of their own, but the site-wide default
1526 // image still applies — without this they fell through to the raw
1527 // logo/site-icon fallback in generate_og_tags() and ignored a
1528 // configured default OG image.
1529 $data['image'] = $this->get_og_image_for_context($settings, null);
1530 $data['twitter_image'] = $this->get_twitter_image_for_context($settings, null);
1531 }
1532
1533 return $data;
1534 }
1535
1536 /**
1537 * Get Open Graph image for context with proper fallback
1538 *
1539 * @since 1.0.0
1540 *
1541 * @param array $settings Social meta settings
1542 * @param \WP_Post|null $post Optional. Post object for post-specific images
1543 * @return string Image URL or empty string
1544 */
1545 private function get_og_image_for_context(array $settings, ?\WP_Post $post = null): string {
1546 // For posts, check featured image first
1547 if ($post) {
1548 $image_id = get_post_thumbnail_id($post);
1549 if ($image_id) {
1550 $image_data = wp_get_attachment_image_src($image_id, 'large');
1551 if (!empty($image_data[0])) {
1552 return $image_data[0];
1553 }
1554 }
1555 }
1556
1557 // Fallback to configured Open Graph image
1558 if (!empty($settings['default_og_image'])) {
1559 return $settings['default_og_image'];
1560 }
1561
1562 // Final fallback to generic default image
1563 if (!empty($settings['default_image'])) {
1564 return $settings['default_image'];
1565 }
1566
1567 // Last-resort fallback to the site logo / site icon. Resolving it here
1568 // (rather than late inside generate_og_tags()) writes it back to the
1569 // shared $data['image'], so generate_twitter_tags() and
1570 // determine_twitter_card_type() see the same image: twitter:image is
1571 // emitted and the card is promoted to summary_large_image, and the
1572 // image is routed through optimize_image_for_platform() so
1573 // og:image:width/height/type/alt companions are produced.
1574 return $this->get_default_social_image();
1575 }
1576
1577 /**
1578 * Get Twitter image for context with proper fallback
1579 *
1580 * @since 1.0.0
1581 *
1582 * @param array $settings Social meta settings
1583 * @param \WP_Post|null $post Optional. Post object for post-specific images
1584 * @return string Image URL or empty string
1585 */
1586 private function get_twitter_image_for_context(array $settings, ?\WP_Post $post = null): string {
1587 // For posts, check for post-specific Twitter image meta first (if implemented)
1588 if ($post) {
1589 // Check for post-specific Twitter image meta (future enhancement)
1590 $post_twitter_image = get_post_meta($post->ID, '_thinkrank_twitter_image', true);
1591 if (!empty($post_twitter_image)) {
1592 return $post_twitter_image;
1593 }
1594
1595 // Check featured image as fallback for posts
1596 $image_id = get_post_thumbnail_id($post);
1597 if ($image_id) {
1598 $image_data = wp_get_attachment_image_src($image_id, 'large');
1599 if (!empty($image_data[0])) {
1600 return $image_data[0];
1601 }
1602 }
1603 }
1604
1605 // Prioritize Twitter-specific default image
1606 if (!empty($settings['default_twitter_image'])) {
1607 return $settings['default_twitter_image'];
1608 }
1609
1610 // Fallback to Open Graph default image
1611 if (!empty($settings['default_og_image'])) {
1612 return $settings['default_og_image'];
1613 }
1614
1615 // Final fallback to generic default image
1616 if (!empty($settings['default_image'])) {
1617 return $settings['default_image'];
1618 }
1619
1620 return '';
1621 }
1622
1623 /**
1624 * Get social media description for post
1625 *
1626 * @since 1.0.0
1627 *
1628 * @param \WP_Post $post Post object
1629 * @return string Social media description
1630 */
1631 private function get_social_description(\WP_Post $post): string {
1632 // Try excerpt first
1633 $description = get_the_excerpt($post);
1634
1635 // If no excerpt, generate from content
1636 if (empty($description)) {
1637 $content = wp_strip_all_tags($post->post_content);
1638 $description = wp_trim_words($content, 30, '...');
1639 }
1640
1641 // If still empty, use site description
1642 if (empty($description)) {
1643 $description = get_bloginfo('description');
1644 }
1645
1646 return $description;
1647 }
1648
1649 /**
1650 * Determine Open Graph type based on context
1651 *
1652 * @since 1.0.0
1653 *
1654 * @param string $context Context type
1655 * @param array $data Content data
1656 * @return string OG type
1657 */
1658 private function determine_og_type(string $context, array $data): string {
1659 switch ($context) {
1660 case 'post':
1661 return 'article';
1662 case 'product':
1663 return 'product';
1664 case 'page':
1665 case 'site':
1666 default:
1667 return 'website';
1668 }
1669 }
1670
1671 /**
1672 * Determine Twitter Card type based on content
1673 *
1674 * @since 1.0.0
1675 *
1676 * @param array $data Content data
1677 * @param string $context Context type
1678 * @return string Twitter Card type
1679 */
1680 private function determine_twitter_card_type(array $data, string $context): string {
1681 // Use a large-image card when a Twitter image will actually be emitted.
1682 // twitter:image resolves to the twitter-specific image first, then the OG
1683 // image, so key the card type off the same precedence.
1684 $twitter_image = !empty($data['twitter_image']) ? $data['twitter_image'] : ($data['image'] ?? '');
1685 return !empty($twitter_image) ? 'summary_large_image' : 'summary';
1686 }
1687
1688 /**
1689 * Optimize title for platform requirements
1690 *
1691 * @since 1.0.0
1692 *
1693 * @param string $title Original title
1694 * @param string $platform Target platform
1695 * @return string Optimized title
1696 */
1697 private function optimize_title_for_platform(string $title, string $platform): string {
1698 if (empty($title)) {
1699 return get_bloginfo('name');
1700 }
1701
1702 $max_length = $this->supported_platforms[$platform]['title_max_length'] ?? 60;
1703
1704 // Multibyte-safe: byte-based substr() would split characters in
1705 // CJK/Bengali/accented titles (WP ships an mbstring fallback).
1706 if (mb_strlen($title) <= $max_length) {
1707 return $title;
1708 }
1709
1710 // Truncate at word boundary
1711 $truncated = wp_trim_words($title, 10, '');
1712 if (mb_strlen($truncated) <= $max_length) {
1713 return $truncated;
1714 }
1715
1716 // Hard truncate if necessary
1717 return mb_substr($title, 0, $max_length - 3) . '...';
1718 }
1719
1720 /**
1721 * Optimize description for platform requirements
1722 *
1723 * @since 1.0.0
1724 *
1725 * @param string $description Original description
1726 * @param string $platform Target platform
1727 * @return string Optimized description
1728 */
1729 private function optimize_description_for_platform(string $description, string $platform): string {
1730 if (empty($description)) {
1731 return get_bloginfo('description');
1732 }
1733
1734 $max_length = $this->supported_platforms[$platform]['description_max_length'] ?? 160;
1735
1736 // Multibyte-safe: byte-based substr() would split characters in
1737 // CJK/Bengali/accented descriptions (WP ships an mbstring fallback).
1738 if (mb_strlen($description) <= $max_length) {
1739 return $description;
1740 }
1741
1742 // Truncate at word boundary
1743 $truncated = wp_trim_words($description, 25, '');
1744 if (mb_strlen($truncated) <= $max_length) {
1745 return $truncated;
1746 }
1747
1748 // Hard truncate if necessary
1749 return mb_substr($description, 0, $max_length - 3) . '...';
1750 }
1751
1752 /**
1753 * Optimize image for platform requirements
1754 *
1755 * @since 1.0.0
1756 *
1757 * @param string $image_url Image URL
1758 * @param string $platform Target platform
1759 * @return array Optimized image data
1760 */
1761 private function optimize_image_for_platform(string $image_url, string $platform): array {
1762 $image_data = [
1763 'url' => $image_url,
1764 'width' => '',
1765 'height' => '',
1766 'alt' => '',
1767 'type' => '',
1768 'valid' => false,
1769 'warnings' => []
1770 ];
1771
1772 if (empty($image_url)) {
1773 return $image_data;
1774 }
1775
1776 // Get image metadata
1777 $attachment_id = attachment_url_to_postid($image_url);
1778 if ($attachment_id) {
1779 $image_meta = wp_get_attachment_metadata($attachment_id);
1780 $image_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
1781 $mime_type = get_post_mime_type($attachment_id);
1782
1783 if ($image_meta && isset($image_meta['width'], $image_meta['height'])) {
1784 $width = (int) $image_meta['width'];
1785 $height = (int) $image_meta['height'];
1786
1787 $image_data['alt'] = $image_alt ?: '';
1788 $image_data['type'] = $mime_type ?: '';
1789
1790 // SVGs and other vector uploads store 0x0 metadata. Dimension
1791 // checks are meaningless there and dividing by 0 is fatal.
1792 if ($width > 0 && $height > 0) {
1793 $image_data['width'] = $width;
1794 $image_data['height'] = $height;
1795
1796 // Validate against platform requirements
1797 $platform_spec = $this->supported_platforms[$platform] ?? [];
1798 $min_width = $platform_spec['image_min_width'] ?? 300;
1799 $min_height = $platform_spec['image_min_height'] ?? 200;
1800
1801 if ($width >= $min_width && $height >= $min_height) {
1802 $image_data['valid'] = true;
1803 } else {
1804 $image_data['warnings'][] = "Image dimensions ({$width}x{$height}) are below recommended minimum ({$min_width}x{$min_height}) for {$platform}";
1805 }
1806
1807 // Check aspect ratio if specified
1808 if (isset($platform_spec['image_recommended_ratio'])) {
1809 $actual_ratio = $width / $height;
1810 $recommended_ratio = $platform_spec['image_recommended_ratio'];
1811 $ratio_tolerance = 0.1;
1812
1813 if (abs($actual_ratio - $recommended_ratio) > $ratio_tolerance) {
1814 $image_data['warnings'][] = sprintf(
1815 "Image aspect ratio (%.2f) differs from recommended ratio (%.2f) for %s",
1816 $actual_ratio,
1817 $recommended_ratio,
1818 $platform
1819 );
1820 }
1821 }
1822 }
1823 }
1824 }
1825
1826 return $image_data;
1827 }
1828
1829 /**
1830 * Get default social image
1831 *
1832 * @since 1.0.0
1833 *
1834 * @return string Default social image URL
1835 */
1836 private function get_default_social_image(): string {
1837 // Try custom logo first
1838 $custom_logo_id = get_theme_mod('custom_logo');
1839 if ($custom_logo_id) {
1840 $logo_data = wp_get_attachment_image_src($custom_logo_id, 'large');
1841 if ($logo_data) {
1842 return $logo_data[0];
1843 }
1844 }
1845
1846 // Try site icon
1847 $site_icon_id = get_option('site_icon');
1848 if ($site_icon_id) {
1849 $icon_data = wp_get_attachment_image_src($site_icon_id, 'large');
1850 if ($icon_data) {
1851 return $icon_data[0];
1852 }
1853 }
1854
1855 return '';
1856 }
1857
1858 /**
1859 * Get Open Graph locale
1860 *
1861 * @since 1.0.0
1862 *
1863 * @return string OG locale
1864 */
1865 private function get_og_locale(): string {
1866 /**
1867 * Filter the locale used for og:locale.
1868 *
1869 * Defaults to get_locale(), which only tracks the active language once
1870 * that language's translation files are installed — on a multilingual
1871 * site without them every translated URL still reports the default
1872 * locale. The multilingual integration answers with the locale its
1873 * provider reports for the language actually being viewed.
1874 *
1875 * @since 1.23.0
1876 *
1877 * @param string $locale Locale for the current request.
1878 */
1879 $locale = (string) apply_filters('thinkrank_og_locale', get_locale());
1880
1881 // Convert WordPress locale to OG locale format for the few that differ
1882 // from the xx_YY form (e.g. bare 'ja').
1883 $og_locale_map = [
1884 'ja' => 'ja_JP',
1885 ];
1886
1887 if (isset($og_locale_map[$locale])) {
1888 return $og_locale_map[$locale];
1889 }
1890
1891 // Fall back to the actual site locale (normalized to xx_YY) rather than
1892 // mislabeling every unmapped language as en_US.
1893 if (preg_match('/^[a-z]{2,3}_[A-Z]{2}$/', $locale)) {
1894 return $locale;
1895 }
1896
1897 // Bare language code (e.g. 'nl') → best-effort xx_XX.
1898 if (preg_match('/^([a-z]{2,3})$/', $locale, $m)) {
1899 return $m[1] . '_' . strtoupper($m[1]);
1900 }
1901
1902 return 'en_US';
1903 }
1904
1905 /**
1906 * Get current URL
1907 *
1908 * @since 1.0.0
1909 *
1910 * @return string Current URL
1911 */
1912 private function get_current_url(): string {
1913 if (is_admin()) {
1914 return home_url();
1915 }
1916
1917 global $wp;
1918 return home_url(add_query_arg([], $wp->request));
1919 }
1920
1921 /**
1922 * Get Twitter site handle
1923 *
1924 * @since 1.0.0
1925 *
1926 * @return string Twitter site handle
1927 */
1928 private function get_twitter_site_handle(): string {
1929 $settings = $this->get_settings('site');
1930 $username = $settings['twitter_username'] ?? '';
1931
1932 if (empty($username)) {
1933 return '';
1934 }
1935
1936 // Ensure username starts with @ for meta tag output
1937 return '@' . ltrim($username, '@');
1938 }
1939
1940 /**
1941 * Get Twitter creator handle
1942 *
1943 * @since 1.0.0
1944 *
1945 * @return string Twitter creator handle
1946 */
1947 private function get_twitter_creator_handle(): string {
1948 $settings = $this->get_settings('site');
1949 $creator = $settings['twitter_creator'] ?? '';
1950
1951 if (empty($creator)) {
1952 return '';
1953 }
1954
1955 // Ensure creator starts with @ for meta tag output
1956 return '@' . ltrim($creator, '@');
1957 }
1958
1959 /**
1960 * Add context-specific Open Graph tags
1961 *
1962 * @since 1.0.0
1963 *
1964 * @param array $og_tags OG tags array
1965 * @param string $context Context type
1966 * @param array $data Content data
1967 * @param string $og_type OG type
1968 * @return array Updated OG tags
1969 */
1970 private function add_context_specific_og_tags(array $og_tags, string $context, array $data, string $og_type): array {
1971 switch ($og_type) {
1972 case 'article':
1973 if (!empty($data['author']['name'])) {
1974 $og_tags['article:author'] = $data['author']['name'];
1975 }
1976 if (!empty($data['published_time'])) {
1977 $og_tags['article:published_time'] = $data['published_time'];
1978 }
1979 if (!empty($data['modified_time'])) {
1980 $og_tags['article:modified_time'] = $data['modified_time'];
1981 }
1982 // article:section — the post's primary category (parity with the
1983 // basic emitter, which the active path previously omitted).
1984 if (!empty($data['post_id'])) {
1985 $categories = get_the_category((int) $data['post_id']);
1986 if (!empty($categories) && !is_wp_error($categories)) {
1987 $og_tags['article:section'] = $categories[0]->name;
1988 }
1989 }
1990 break;
1991 case 'product':
1992 // Product-specific tags would be added here
1993 // This could be extended with price, availability, etc.
1994 break;
1995 }
1996
1997 // Add local business Open Graph tags if business data is available
1998 $og_tags = $this->add_local_business_og_tags($og_tags, $data);
1999
2000 return $og_tags;
2001 }
2002
2003 /**
2004 * Add local business Open Graph tags
2005 *
2006 * @since 1.0.0
2007 *
2008 * @param array $og_tags OG tags array
2009 * @param array $data Content data
2010 * @return array Updated OG tags with local business information
2011 */
2012 private function add_local_business_og_tags(array $og_tags, array $data): array {
2013 // Get business data from Site Identity settings
2014 $business_data = $this->get_local_business_data();
2015
2016 if (empty($business_data) || empty($business_data['business_name'])) {
2017 return $og_tags;
2018 }
2019
2020 // Add business contact data Open Graph tags
2021 if (!empty($business_data['business_address'])) {
2022 $og_tags['business:contact_data:street_address'] = $business_data['business_address'];
2023 }
2024
2025 if (!empty($business_data['business_city'])) {
2026 $og_tags['business:contact_data:locality'] = $business_data['business_city'];
2027 }
2028
2029 if (!empty($business_data['business_state'])) {
2030 $og_tags['business:contact_data:region'] = $business_data['business_state'];
2031 }
2032
2033 if (!empty($business_data['business_postal_code'])) {
2034 $og_tags['business:contact_data:postal_code'] = $business_data['business_postal_code'];
2035 }
2036
2037 if (!empty($business_data['business_country'])) {
2038 $og_tags['business:contact_data:country_name'] = $business_data['business_country'];
2039 }
2040
2041 if (!empty($business_data['business_phone'])) {
2042 $og_tags['business:contact_data:phone_number'] = $business_data['business_phone'];
2043 }
2044
2045 if (!empty($business_data['business_email'])) {
2046 $og_tags['business:contact_data:email'] = $business_data['business_email'];
2047 }
2048
2049 // Add business hours if available
2050 if (!empty($business_data['business_hours']) && is_array($business_data['business_hours'])) {
2051 $formatted_hours = $this->format_business_hours_for_og($business_data['business_hours']);
2052 if (!empty($formatted_hours)) {
2053 $og_tags['business:hours'] = $formatted_hours;
2054 }
2055 }
2056
2057 // Add business website
2058 if (!empty($business_data['business_website'])) {
2059 $og_tags['business:contact_data:website'] = $business_data['business_website'];
2060 }
2061
2062 // Add coordinates if available
2063 if (!empty($business_data['business_latitude']) && !empty($business_data['business_longitude'])) {
2064 $og_tags['place:location:latitude'] = $business_data['business_latitude'];
2065 $og_tags['place:location:longitude'] = $business_data['business_longitude'];
2066 }
2067
2068 return $og_tags;
2069 }
2070
2071 /**
2072 * Get local business data from Site Identity settings
2073 *
2074 * @since 1.0.0
2075 *
2076 * @return array Business data array
2077 */
2078 private function get_local_business_data(): array {
2079 // Try to get Site Identity Manager
2080 if (!class_exists('ThinkRank\\SEO\\Site_Identity_Manager')) {
2081 require_once THINKRANK_PLUGIN_DIR . 'includes/seo/class-site-identity-manager.php';
2082 }
2083
2084 $site_identity_manager = new \ThinkRank\SEO\Site_Identity_Manager();
2085 $settings = $site_identity_manager->get_settings('site');
2086
2087 // Only return data if local SEO is enabled
2088 if (empty($settings['local_seo_enabled'])) {
2089 return [];
2090 }
2091
2092 return [
2093 'business_name' => $settings['business_name'] ?? '',
2094 'business_address' => $settings['business_address'] ?? '',
2095 'business_city' => $settings['business_city'] ?? '',
2096 'business_state' => $settings['business_state'] ?? '',
2097 'business_postal_code' => $settings['business_postal_code'] ?? '',
2098 'business_country' => $settings['business_country'] ?? '',
2099 'business_phone' => $settings['business_phone'] ?? '',
2100 'business_email' => $settings['business_email'] ?? '',
2101 'business_hours' => $settings['business_hours'] ?? [],
2102 'business_website' => $settings['business_website'] ?? home_url(),
2103 'business_latitude' => $settings['business_latitude'] ?? '',
2104 'business_longitude' => $settings['business_longitude'] ?? ''
2105 ];
2106 }
2107
2108 /**
2109 * Format business hours for Open Graph tags
2110 *
2111 * @since 1.0.0
2112 *
2113 * @param array $business_hours Business hours array
2114 * @return string Formatted hours string
2115 */
2116 private function format_business_hours_for_og(array $business_hours): string {
2117 $formatted_days = [];
2118
2119 $day_names = [
2120 'monday' => 'Monday',
2121 'tuesday' => 'Tuesday',
2122 'wednesday' => 'Wednesday',
2123 'thursday' => 'Thursday',
2124 'friday' => 'Friday',
2125 'saturday' => 'Saturday',
2126 'sunday' => 'Sunday'
2127 ];
2128
2129 foreach ($day_names as $day => $display_name) {
2130 if (isset($business_hours[$day]) && !empty($business_hours[$day])) {
2131 $day_data = $business_hours[$day];
2132
2133 if (!empty($day_data['closed']) || empty($day_data['open']) || empty($day_data['close'])) {
2134 $formatted_days[] = $display_name . ': Closed';
2135 } else {
2136 $formatted_days[] = $display_name . ': ' . $day_data['open'] . ' - ' . $day_data['close'];
2137 }
2138 }
2139 }
2140
2141 return implode('; ', $formatted_days);
2142 }
2143
2144 /**
2145 * Apply platform-specific optimizations
2146 *
2147 * @since 1.0.0
2148 *
2149 * @param array $og_tags OG tags array
2150 * @param string $platform Target platform
2151 * @param array $data Content data
2152 * @return array Optimized OG tags
2153 */
2154 private function apply_platform_specific_optimizations(array $og_tags, string $platform, array $data): array {
2155 $settings = $this->get_settings('site');
2156
2157 switch ($platform) {
2158 case 'linkedin':
2159 // LinkedIn prefers professional content
2160 if ($settings['enable_linkedin'] ?? false) {
2161 if (isset($og_tags['og:description'])) {
2162 $og_tags['og:description'] = $this->make_description_professional($og_tags['og:description']);
2163 }
2164 // Add LinkedIn-specific type if appropriate
2165 if ($og_tags['og:type'] === 'article') {
2166 $og_tags['article:author'] = $data['author'] ?? '';
2167 }
2168 }
2169 break;
2170
2171 case 'pinterest':
2172 // Pinterest prefers descriptive content
2173 if ($settings['enable_pinterest'] ?? false) {
2174 if (isset($og_tags['og:description'])) {
2175 $og_tags['og:description'] = $this->make_description_descriptive($og_tags['og:description']);
2176 }
2177 // Pinterest prefers article type for rich pins
2178 if (in_array($og_tags['og:type'], ['website', 'blog'])) {
2179 $og_tags['og:type'] = 'article';
2180 }
2181 }
2182 break;
2183
2184 case 'instagram':
2185 // Instagram optimizations
2186 if ($settings['enable_instagram'] ?? false) {
2187 // Instagram prefers square or vertical images
2188 if (isset($og_tags['og:description'])) {
2189 $og_tags['og:description'] = $this->make_description_engaging($og_tags['og:description']);
2190 }
2191 }
2192 break;
2193
2194 case 'tiktok':
2195 // TikTok optimizations
2196 if ($settings['enable_tiktok'] ?? false) {
2197 // TikTok prefers short, catchy descriptions
2198 if (isset($og_tags['og:description'])) {
2199 $og_tags['og:description'] = $this->make_description_catchy($og_tags['og:description']);
2200 }
2201 }
2202 break;
2203 }
2204
2205 return $og_tags;
2206 }
2207
2208 /**
2209 * Make description more professional for LinkedIn
2210 *
2211 * @since 1.0.0
2212 *
2213 * @param string $description Original description
2214 * @return string Professional description
2215 */
2216 private function make_description_professional(string $description): string {
2217 // Remove casual language and emojis, add professional tone
2218 $description = preg_replace('/[^\w\s\.,!?-]/', '', $description);
2219
2220 // Add professional keywords if not present
2221 $professional_words = ['insights', 'expertise', 'professional', 'industry', 'business'];
2222 if (!preg_match('/\b(' . implode('|', $professional_words) . ')\b/i', $description)) {
2223 $description = 'Professional insights: ' . $description;
2224 }
2225
2226 return $description;
2227 }
2228
2229 /**
2230 * Make description more descriptive for Pinterest
2231 *
2232 * @since 1.0.0
2233 *
2234 * @param string $description Original description
2235 * @return string Descriptive description
2236 */
2237 private function make_description_descriptive(string $description): string {
2238 // Pinterest users love detailed, searchable descriptions
2239 $descriptive_words = ['discover', 'explore', 'learn', 'find', 'ideas'];
2240
2241 if (!preg_match('/\b(' . implode('|', $descriptive_words) . ')\b/i', $description)) {
2242 $description = 'Discover ' . lcfirst($description);
2243 }
2244
2245 return $description;
2246 }
2247
2248 /**
2249 * Make description engaging for Instagram
2250 *
2251 * @since 1.0.0
2252 *
2253 * @param string $description Original description
2254 * @return string Engaging description
2255 */
2256 private function make_description_engaging(string $description): string {
2257 // Instagram prefers engaging, visual language
2258 $engaging_words = ['amazing', 'stunning', 'beautiful', 'incredible', 'inspiring'];
2259
2260 if (!preg_match('/\b(' . implode('|', $engaging_words) . ')\b/i', $description)) {
2261 $description = '' . $description;
2262 }
2263
2264 return $description;
2265 }
2266
2267 /**
2268 * Make description catchy for TikTok
2269 *
2270 * @since 1.0.0
2271 *
2272 * @param string $description Original description
2273 * @return string Catchy description
2274 */
2275 private function make_description_catchy(string $description): string {
2276 // TikTok prefers short, catchy descriptions
2277 $catchy_words = ['viral', 'trending', 'must-see', 'epic', 'mind-blowing'];
2278
2279 // Limit to 100 characters for TikTok
2280 if (strlen($description) > 100) {
2281 $description = substr($description, 0, 97) . '...';
2282 }
2283
2284 if (!preg_match('/\b(' . implode('|', $catchy_words) . ')\b/i', $description)) {
2285 $description = '🔥 ' . $description;
2286 }
2287
2288 return $description;
2289 }
2290
2291 /**
2292 * Add Twitter Card specific tags
2293 *
2294 * @since 1.0.0
2295 *
2296 * @param array $twitter_tags Twitter tags array
2297 * @param string $card_type Card type
2298 * @param array $data Content data
2299 * @param string $context Context type
2300 * @return array Updated Twitter tags
2301 */
2302 private function add_twitter_card_specific_tags(array $twitter_tags, string $card_type, array $data, string $context): array {
2303 // The content extractor only produces summary / summary_large_image
2304 // cards, so the player/app card variants were dead code that read keys
2305 // (video_url, app_name, …) the extractor never sets. Kept as a filterable
2306 // extension point for add-ons that do populate richer card data.
2307 return apply_filters('thinkrank_twitter_card_specific_tags', $twitter_tags, $card_type, $data, $context);
2308 }
2309
2310 /**
2311 * Generate Open Graph preview
2312 *
2313 * @since 1.0.0
2314 *
2315 * @param array $og_tags OG tags
2316 * @param string $platform Platform name
2317 * @param array $preview Preview array
2318 * @return array Updated preview
2319 */
2320 private function generate_og_preview(array $og_tags, string $platform, array $preview): array {
2321 $preview['title'] = $og_tags['og:title'] ?? '';
2322 $preview['description'] = $og_tags['og:description'] ?? '';
2323 $preview['image'] = $og_tags['og:image'] ?? '';
2324 $preview['preview_url'] = $og_tags['og:url'] ?? '';
2325
2326 // Validate required fields
2327 $required_fields = ['og:title', 'og:type', 'og:image', 'og:url'];
2328 $missing_fields = [];
2329
2330 foreach ($required_fields as $field) {
2331 if (empty($og_tags[$field])) {
2332 $missing_fields[] = $field;
2333 }
2334 }
2335
2336 if (empty($missing_fields)) {
2337 $preview['valid'] = true;
2338 } else {
2339 $preview['warnings'][] = 'Missing required fields: ' . implode(', ', $missing_fields);
2340 }
2341
2342 // Platform-specific validation
2343 $platform_spec = $this->supported_platforms[$platform] ?? [];
2344 if (isset($platform_spec['title_max_length']) && strlen($preview['title']) > $platform_spec['title_max_length']) {
2345 $preview['warnings'][] = "Title exceeds {$platform} maximum length of {$platform_spec['title_max_length']} characters";
2346 }
2347
2348 return $preview;
2349 }
2350
2351 /**
2352 * Generate Twitter preview
2353 *
2354 * @since 1.0.0
2355 *
2356 * @param array $twitter_tags Twitter tags
2357 * @param array $preview Preview array
2358 * @return array Updated preview
2359 */
2360 private function generate_twitter_preview(array $twitter_tags, array $preview): array {
2361 $preview['title'] = $twitter_tags['twitter:title'] ?? '';
2362 $preview['description'] = $twitter_tags['twitter:description'] ?? '';
2363 $preview['image'] = $twitter_tags['twitter:image'] ?? '';
2364
2365 // Validate required fields
2366 $required_fields = ['twitter:card', 'twitter:title'];
2367 $missing_fields = [];
2368
2369 foreach ($required_fields as $field) {
2370 if (empty($twitter_tags[$field])) {
2371 $missing_fields[] = $field;
2372 }
2373 }
2374
2375 if (empty($missing_fields)) {
2376 $preview['valid'] = true;
2377 } else {
2378 $preview['warnings'][] = 'Missing required fields: ' . implode(', ', $missing_fields);
2379 }
2380
2381 // Twitter-specific validation
2382 $twitter_spec = $this->supported_platforms['twitter'];
2383 if (strlen($preview['title']) > $twitter_spec['title_max_length']) {
2384 $preview['warnings'][] = "Title exceeds Twitter maximum length of {$twitter_spec['title_max_length']} characters";
2385 }
2386
2387 return $preview;
2388 }
2389
2390 /**
2391 * Generate Pinterest preview
2392 *
2393 * @since 1.0.0
2394 *
2395 * @param array $og_tags OG tags
2396 * @param array $preview Preview array
2397 * @return array Updated preview
2398 */
2399 private function generate_pinterest_preview(array $og_tags, array $preview): array {
2400 $preview['title'] = $og_tags['og:title'] ?? '';
2401 $preview['description'] = $og_tags['og:description'] ?? '';
2402 $preview['image'] = $og_tags['og:image'] ?? '';
2403 $preview['preview_url'] = $og_tags['og:url'] ?? '';
2404
2405 // Validate required fields for Pinterest
2406 $required_fields = ['og:title', 'og:image', 'og:url'];
2407 $missing_fields = [];
2408
2409 foreach ($required_fields as $field) {
2410 if (empty($og_tags[$field])) {
2411 $missing_fields[] = $field;
2412 }
2413 }
2414
2415 if (empty($missing_fields)) {
2416 $preview['valid'] = true;
2417 } else {
2418 $preview['warnings'][] = 'Missing required fields: ' . implode(', ', $missing_fields);
2419 }
2420
2421 // Pinterest-specific validation and suggestions
2422 $pinterest_spec = $this->supported_platforms['pinterest'] ?? [];
2423
2424 // Title length validation
2425 if (isset($pinterest_spec['title_max_length']) && strlen($preview['title']) > $pinterest_spec['title_max_length']) {
2426 $preview['warnings'][] = "Title exceeds Pinterest maximum length of {$pinterest_spec['title_max_length']} characters";
2427 }
2428
2429 // Description length validation
2430 if (isset($pinterest_spec['description_max_length']) && strlen($preview['description']) > $pinterest_spec['description_max_length']) {
2431 $preview['warnings'][] = "Description exceeds Pinterest maximum length of {$pinterest_spec['description_max_length']} characters";
2432 }
2433
2434 // Image dimension suggestions for Pinterest
2435 if (!empty($preview['image'])) {
2436 $image_data = $this->optimize_image_for_platform($preview['image'], 'pinterest');
2437 if (!empty($image_data['width']) && !empty($image_data['height'])) {
2438 $aspect_ratio = $image_data['width'] / $image_data['height'];
2439
2440 // Pinterest prefers vertical images (2:3 ratio is optimal)
2441 if ($aspect_ratio > 1) {
2442 $preview['suggestions'][] = 'Pinterest performs better with vertical images (2:3 aspect ratio recommended)';
2443 } elseif ($aspect_ratio < 0.6) {
2444 $preview['suggestions'][] = 'Image is very tall - consider a 2:3 aspect ratio for optimal Pinterest performance';
2445 }
2446
2447 // Minimum size recommendations
2448 if ($image_data['width'] < 600) {
2449 $preview['suggestions'][] = 'Pinterest recommends images at least 600px wide for better quality';
2450 }
2451 }
2452 }
2453
2454 return $preview;
2455 }
2456
2457 /**
2458 * Generate platform-specific meta tags
2459 *
2460 * @since 1.0.0
2461 *
2462 * @param array $settings Settings array
2463 * @return array Platform-specific meta tags
2464 */
2465 private function generate_platform_meta_tags(array $settings): array {
2466 $platform_tags = [];
2467
2468 // Facebook meta tags
2469 if (!empty($settings['facebook_app_id'])) {
2470 $platform_tags['fb:app_id'] = $settings['facebook_app_id'];
2471 }
2472
2473 if (!empty($settings['facebook_admins'])) {
2474 $platform_tags['fb:admins'] = $settings['facebook_admins'];
2475 }
2476
2477 // Pinterest site verification
2478 if (!empty($settings['pinterest_site_verification'])) {
2479 $platform_tags['pinterest-site-verification'] = $settings['pinterest_site_verification'];
2480 }
2481
2482 // Instagram verification (if enabled)
2483 if (!empty($settings['instagram_verification'])) {
2484 $platform_tags['instagram-site-verification'] = $settings['instagram_verification'];
2485 }
2486
2487 // TikTok verification (if enabled)
2488 if (!empty($settings['tiktok_verification'])) {
2489 $platform_tags['tiktok-site-verification'] = $settings['tiktok_verification'];
2490 }
2491
2492 // YouTube channel verification (if enabled)
2493 if (!empty($settings['youtube_channel_id'])) {
2494 $platform_tags['youtube-channel-id'] = $settings['youtube_channel_id'];
2495 }
2496
2497 // WhatsApp Business verification (if enabled)
2498 if (!empty($settings['whatsapp_business_id'])) {
2499 $platform_tags['whatsapp-business-id'] = $settings['whatsapp_business_id'];
2500 }
2501
2502 return $platform_tags;
2503 }
2504
2505 /**
2506 * Convert OG, Twitter, and Platform tags to HTML meta tags
2507 *
2508 * @since 1.0.0
2509 *
2510 * @param array $og_tags Open Graph tags
2511 * @param array $twitter_tags Twitter tags
2512 * @param array $platform_tags Platform-specific tags
2513 * @return array HTML meta tags
2514 */
2515 private function convert_to_meta_tags(array $og_tags, array $twitter_tags, array $platform_tags = []): array {
2516 $meta_tags = [];
2517
2518 // Convert OG tags
2519 foreach ($og_tags as $property => $content) {
2520 if (!empty($content)) {
2521 $meta_tags[] = [
2522 'property' => esc_attr($property),
2523 'content' => esc_attr($content)
2524 ];
2525 }
2526 }
2527
2528 // Convert Twitter tags
2529 foreach ($twitter_tags as $name => $content) {
2530 if (!empty($content)) {
2531 $meta_tags[] = [
2532 'name' => esc_attr($name),
2533 'content' => esc_attr($content)
2534 ];
2535 }
2536 }
2537
2538 // Convert Platform tags
2539 foreach ($platform_tags as $name => $content) {
2540 if (!empty($content)) {
2541 // Determine if it should be property or name attribute
2542 if (strpos($name, 'fb:') === 0) {
2543 // Facebook tags use property attribute
2544 $meta_tags[] = [
2545 'property' => esc_attr($name),
2546 'content' => esc_attr($content)
2547 ];
2548 } else {
2549 // Other platform tags use name attribute
2550 $meta_tags[] = [
2551 'name' => esc_attr($name),
2552 'content' => esc_attr($content)
2553 ];
2554 }
2555 }
2556 }
2557
2558 return $meta_tags;
2559 }
2560
2561 /**
2562 * Validate social image
2563 *
2564 * @since 1.0.0
2565 *
2566 * @param string $image_url Image URL to validate
2567 * @return array Validation results
2568 */
2569 private function validate_social_image(string $image_url): array {
2570 $validation = [
2571 'valid' => false,
2572 'warnings' => [],
2573 'suggestions' => []
2574 ];
2575
2576 if (empty($image_url)) {
2577 $validation['warnings'][] = 'No image provided';
2578 return $validation;
2579 }
2580
2581 // Check if URL is valid
2582 if (!filter_var($image_url, FILTER_VALIDATE_URL)) {
2583 $validation['warnings'][] = 'Invalid image URL';
2584 return $validation;
2585 }
2586
2587 // Get image metadata if it's a local attachment
2588 $attachment_id = attachment_url_to_postid($image_url);
2589 if ($attachment_id) {
2590 $image_meta = wp_get_attachment_metadata($attachment_id);
2591 $meta_width = isset($image_meta['width']) ? (int) $image_meta['width'] : 0;
2592 $meta_height = isset($image_meta['height']) ? (int) $image_meta['height'] : 0;
2593
2594 // SVGs and other vector uploads store 0x0 metadata — skip the
2595 // dimension/ratio checks instead of dividing by 0.
2596 if ($image_meta && $meta_width > 0 && $meta_height > 0) {
2597 // Check minimum dimensions for major platforms
2598 $min_width = 600; // Facebook minimum
2599 $min_height = 315; // Facebook minimum
2600
2601 if ($meta_width >= $min_width && $meta_height >= $min_height) {
2602 $validation['valid'] = true;
2603 } else {
2604 $validation['warnings'][] = "Image dimensions ({$meta_width}x{$meta_height}) are below recommended minimum ({$min_width}x{$min_height})";
2605 }
2606
2607 // Check file size
2608 $file_path = get_attached_file($attachment_id);
2609 if ($file_path && file_exists($file_path)) {
2610 $file_size = filesize($file_path);
2611 $max_size = 5 * 1024 * 1024; // 5MB
2612
2613 if ($file_size > $max_size) {
2614 $validation['warnings'][] = 'Image file size exceeds 5MB, may not display on some platforms';
2615 }
2616 }
2617
2618 // Check aspect ratio
2619 $aspect_ratio = $meta_width / $meta_height;
2620 if ($aspect_ratio < 1.5 || $aspect_ratio > 2.5) {
2621 $validation['suggestions'][] = 'Consider using an image with 1.91:1 aspect ratio for optimal display';
2622 }
2623 }
2624 } else {
2625 $validation['suggestions'][] = 'External images may not be optimized for social media platforms';
2626 }
2627
2628 return $validation;
2629 }
2630 }
2631