-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaltly.php
More file actions
766 lines (686 loc) · 23.7 KB
/
altly.php
File metadata and controls
766 lines (686 loc) · 23.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
<?php
/**
* Plugin Name: Altly
* Description: Altly is a cutting-edge plugin that seamlessly integrates Altly’s AI-powered alt text generation into your WordPress website, transforming your media library into an accessibility and SEO asset.
* Version: 0.0.1
* Author: Prolific Digital
* Author URI: https://prolificdigital.com
* Plugin URI: https://altly.ai
* Text Domain: altly
* Requires at least: 5.6
* Requires PHP: 7.2
* License: GPL-2.0-or-later
* Tested up to: 6.7
*/
if (! defined('ABSPATH')) {
exit; // Exit if accessed directly.
}
// Define plugin directory and API endpoints.
define('ALTLY_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('ALTLY_PLUGIN_URL', plugin_dir_url(__FILE__));
define('ALTLY_API_VALIDATE_URL', 'https://api.altly.io/v2/validate');
define('ALTLY_API_QUEUE_URL', 'https://api.altly.io/v2/queue');
require 'plugin-update-checker/plugin-update-checker.php';
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;
$myUpdateChecker = PucFactory::buildUpdateChecker(
'https://github.com/prolific-digital/altly-wp/',
__FILE__,
'altly'
);
$myUpdateChecker->getVcsApi()->enableReleaseAssets();
/**
* Plugin activation hook.
*/
function altly_activate() {
add_option('altly_license_key', '');
}
register_activation_hook(__FILE__, 'altly_activate');
/**
* Display admin notice after activation if no license key is set.
*/
function altly_admin_notice() {
if (! current_user_can('manage_options')) {
return;
}
// Sanitize GET input.
$page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
// Avoid displaying notice on the plugin’s own settings page.
if ('altly' === $page) {
return;
}
$license_key = get_option('altly_license_key', '');
if (empty($license_key)) {
// Updated settings URL: now under Media.
$settings_url = admin_url('upload.php?page=altly');
echo '<div class="notice notice-warning is-dismissible">';
echo '<p>Generate Alt Text plugin requires an API license key. Please <a href="' . esc_url($settings_url) . '">enter your API key here</a>.</p>';
echo '</div>';
}
}
add_action('admin_notices', 'altly_admin_notice');
/**
* Register admin menu page under Media.
*/
function altly_register_admin_page() {
add_submenu_page(
'upload.php', // Parent slug for Media
'Generate Alt Text', // Page title
'Generate Alt Text', // Menu title
'manage_options',
'altly', // Page slug
'altly_render_admin_page'
);
}
add_action('admin_menu', 'altly_register_admin_page');
/**
* Render the admin page container (React will mount here).
*/
function altly_render_admin_page() {
?>
<div class="wrap" id="altly-admin-app">
<!-- React App will be rendered here -->
</div>
<?php
}
/**
* Enqueue admin scripts and styles on our settings page.
*/
function altly_enqueue_admin_scripts($hook) {
// The hook for a submenu under Media is "upload_page_altly"
if ('media_page_altly' !== $hook) {
return;
}
// Enqueue the JS file.
$script_path = ALTLY_PLUGIN_DIR . 'build/index.js';
wp_enqueue_script(
'altly-admin-script',
ALTLY_PLUGIN_URL . 'build/index.js',
array('wp-element', 'wp-components', 'wp-api'),
file_exists($script_path) ? filemtime($script_path) : '1.0.0',
true
);
// Enqueue the CSS file if it exists.
$style_path = ALTLY_PLUGIN_DIR . 'build/index.css';
if (file_exists($style_path)) {
wp_enqueue_style(
'altly-admin-style',
ALTLY_PLUGIN_URL . 'build/index.css',
array(),
filemtime($style_path)
);
} else {
// Optionally enqueue a fallback or simply skip it.
wp_enqueue_style(
'altly-admin-style',
ALTLY_PLUGIN_URL . 'build/index.css',
array(),
'1.0.0'
);
}
// Pass necessary settings to our React app.
wp_localize_script('altly-admin-script', 'AltlySettings', array(
'apiKey' => get_option('altly_license_key', ''),
'restUrl' => esc_url_raw(rest_url('altly/v1/')),
'nonce' => wp_create_nonce('wp_rest'),
));
}
add_action('admin_enqueue_scripts', 'altly_enqueue_admin_scripts');
/**
* Register REST API endpoints.
*/
add_action('rest_api_init', function () {
// Endpoint: Retrieve images missing alt text.
register_rest_route('altly/v1', '/images', array(
'methods' => 'GET',
'callback' => 'altly_get_images_missing_alt',
'permission_callback' => function () {
return current_user_can('manage_options');
},
));
// Endpoint: Validate license key.
register_rest_route('altly/v1', '/validate-key', array(
'methods' => 'POST',
'callback' => 'altly_validate_license_key',
'permission_callback' => function () {
return current_user_can('manage_options');
},
));
// Endpoint: Save license key.
register_rest_route('altly/v1', '/save-key', array(
'methods' => 'POST',
'callback' => 'altly_save_license_key',
'permission_callback' => function () {
return current_user_can('manage_options');
},
));
// Endpoint: Bulk generate alt text.
register_rest_route('altly/v1', '/bulk-generate', array(
'methods' => 'POST',
'callback' => 'altly_bulk_generate',
'permission_callback' => function () {
return current_user_can('manage_options');
},
));
});
/**
* Nonce verification helper.
*/
function altly_verify_rest_nonce() {
// Unsash and sanitize the nonce value.
$nonce = isset($_SERVER['HTTP_X_WP_NONCE']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_X_WP_NONCE'])) : '';
if (! $nonce || ! wp_verify_nonce($nonce, 'wp_rest')) {
return false;
}
return true;
}
/**
* Callback to retrieve paginated images missing alt text along with overall stats.
*/
function altly_get_images_missing_alt($request) {
$per_page = isset($request['per_page']) ? intval($request['per_page']) : 12;
if ($per_page < 0) {
$per_page = -1;
}
$args_missing = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => array('image/jpeg', 'image/png'),
'posts_per_page' => $per_page,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_wp_attachment_image_alt',
'compare' => 'NOT EXISTS',
),
array(
'key' => '_wp_attachment_image_alt',
'value' => '',
'compare' => '='
)
),
);
// If fetching all images, disable paging.
if ($per_page == -1) {
$args_missing['nopaging'] = true;
} else {
$page = isset($request['page']) ? absint($request['page']) : 1;
$args_missing['paged'] = $page;
}
$query_missing = new WP_Query($args_missing);
$missing_images = array();
foreach ($query_missing->posts as $post) {
$filePath = get_attached_file($post->ID);
$size = 'N/A';
if (file_exists($filePath)) {
$size = size_format(filesize($filePath));
}
$missing_images[] = array(
'id' => $post->ID,
'link' => admin_url('upload.php?item=' . $post->ID),
'src' => wp_get_attachment_url($post->ID),
'filePath' => $filePath,
'size' => $size,
'queued' => get_post_meta($post->ID, '_altly_queued', true) ? true : false,
);
}
// Query for total images.
$args_total = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => array('image/jpeg', 'image/png'),
'posts_per_page' => -1,
'nopaging' => true,
);
$query_total = new WP_Query($args_total);
$total_images = $query_total->found_posts;
// Query for queued images.
$args_queued = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => array('image/jpeg', 'image/png'),
'posts_per_page' => -1,
'nopaging' => true,
'meta_query' => array(
array(
'key' => '_altly_queued',
'value' => true,
'compare' => '='
)
)
);
$query_queued = new WP_Query($args_queued);
$queued_count = $query_queued->found_posts;
$response_data = array(
'images' => $missing_images,
'stats' => array(
'total_images' => $total_images,
'missing_alt_count' => $query_missing->found_posts,
'queued_count' => $queued_count,
),
);
$response = rest_ensure_response($response_data);
$response->header('X-WP-TotalPages', $query_missing->max_num_pages);
return $response;
}
// Mark image as queued.
add_action('rest_api_init', function () {
register_rest_route('altly/v1', '/mark-queued', array(
'methods' => 'POST',
'callback' => 'altly_mark_queued',
'permission_callback' => function () {
return current_user_can('manage_options');
},
));
});
function altly_mark_queued($request) {
if (! altly_verify_rest_nonce()) {
return new WP_Error('rest_forbidden', __('Nonce verification failed.', 'altly'), array('status' => 403));
}
$params = $request->get_json_params();
if (empty($params['image_id'])) {
return new WP_Error('missing_image_id', 'Missing image ID', array('status' => 400));
}
$image_id = intval($params['image_id']);
// Mark the image as queued by setting a custom meta field.
update_post_meta($image_id, '_altly_queued', true);
return rest_ensure_response(array('success' => true, 'message' => 'Image marked as queued.'));
}
add_action('rest_api_init', function () {
register_rest_route('altly/v1', '/receive-alt', array(
'methods' => 'POST',
'callback' => 'altly_receive_alt_text',
'permission_callback' => 'altly_validate_api_key_for_receive_alt',
));
});
function altly_validate_api_key_for_receive_alt(WP_REST_Request $request) {
$params = $request->get_json_params();
if (empty($params)) {
$raw = wp_unslash(file_get_contents('php://input'));
$params = json_decode($raw, true);
}
if (! isset($params['api_key'])) {
return new WP_Error('missing_api_key', 'Missing API key', array('status' => 401));
}
$provided_key = sanitize_text_field($params['api_key']);
$stored_key = get_option('altly_license_key');
return ($provided_key === $stored_key);
}
function altly_receive_alt_text(WP_REST_Request $request) {
$params = $request->get_json_params();
if (empty($params)) {
$raw = wp_unslash(file_get_contents('php://input'));
$params = json_decode($raw, true);
}
if (! isset($params['image_id']) || ! isset($params['alt_text']) || ! isset($params['api_key'])) {
return new WP_Error('missing_params', 'Missing parameters', array('status' => 400));
}
$image_id = intval($params['image_id']);
$alt_text = sanitize_text_field($params['alt_text']);
// Verify that the image exists and is an attachment.
$image_post = get_post($image_id);
if (! $image_post || $image_post->post_type !== 'attachment') {
return new WP_Error('invalid_image', 'Invalid image ID', array('status' => 400));
}
$current_alt = get_post_meta($image_id, '_wp_attachment_image_alt', true);
if ($current_alt !== $alt_text) {
$updated = update_post_meta($image_id, '_wp_attachment_image_alt', $alt_text);
if ($updated === false) {
$added = add_post_meta($image_id, '_wp_attachment_image_alt', $alt_text, true);
if (! $added) {
return new WP_Error('update_failed', 'Failed to update alt text', array('status' => 500));
}
}
}
// Remove the queue meta now that the alt text is updated.
delete_post_meta($image_id, '_altly_queued');
$final_alt = get_post_meta($image_id, '_wp_attachment_image_alt', true);
return rest_ensure_response(array('success' => true, 'message' => 'Alt text updated.'));
}
add_action('rest_api_init', function () {
register_rest_route('altly/v1', '/clear-alt-text', array(
'methods' => 'POST',
'callback' => 'altly_clear_all_alt_text',
'permission_callback' => function () {
return current_user_can('manage_options');
},
));
});
function altly_clear_all_alt_text() {
if (! altly_verify_rest_nonce()) {
return new WP_Error('rest_forbidden', __('Nonce verification failed.', 'altly'), array('status' => 403));
}
// Get all attachments that have an alt text.
$args = array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'meta_key' => '_wp_attachment_image_alt',
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
delete_post_meta($attachment->ID, '_wp_attachment_image_alt');
}
}
return rest_ensure_response(array(
'success' => true,
'message' => 'All image alt text has been cleared.',
));
}
add_action('rest_api_init', function () {
register_rest_route('altly/v1', '/clear-queue', array(
'methods' => 'POST',
'callback' => 'altly_clear_queue',
'permission_callback' => function () {
return current_user_can('manage_options');
},
));
});
function altly_clear_queue($request) {
if (! altly_verify_rest_nonce()) {
return new WP_Error('rest_forbidden', __('Nonce verification failed.', 'altly'), array('status' => 403));
}
$params = $request->get_json_params();
if (empty($params['image_ids']) || ! is_array($params['image_ids'])) {
return new WP_Error('no_images', 'No image IDs provided', array('status' => 400));
}
foreach ($params['image_ids'] as $image_id) {
delete_post_meta(intval($image_id), '_altly_queued');
}
return rest_ensure_response(array('success' => true, 'message' => 'Queue cleared for provided images.'));
}
/**
* Callback to validate the license key using the /v2/validate endpoint.
*/
function altly_validate_license_key($request) {
if (! altly_verify_rest_nonce()) {
return new WP_Error('rest_forbidden', __('Nonce verification failed.', 'altly'), array('status' => 403));
}
$params = $request->get_json_params();
$license_key = isset($params['licenseKey']) ? sanitize_text_field($params['licenseKey']) : '';
if (empty($license_key)) {
return new WP_Error('no_license', 'License key is required', array('status' => 400));
}
$response = wp_remote_post(ALTLY_API_VALIDATE_URL, array(
'headers' => array(
'Authorization' => 'Bearer ' . $license_key,
),
'body' => array(),
'timeout' => 15,
));
if (is_wp_error($response)) {
return new WP_Error('api_error', 'Failed to connect to validation API', array('status' => 500));
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if (isset($body['error'])) {
return new WP_Error('invalid_license', $body['error'], array('status' => 401));
}
return rest_ensure_response($body);
}
/**
* Callback to save the license key.
*/
function altly_save_license_key($request) {
if (! altly_verify_rest_nonce()) {
return new WP_Error('rest_forbidden', __('Nonce verification failed.', 'altly'), array('status' => 403));
}
$params = $request->get_json_params();
if (empty($params['licenseKey'])) {
return new WP_Error('no_license', 'License key is required', array('status' => 400));
}
update_option('altly_license_key', sanitize_text_field($params['licenseKey']));
return rest_ensure_response(array('success' => true, 'message' => 'License key saved.'));
}
/**
* Callback for bulk generating alt text by sending images to the /v2/queue endpoint.
*/
function altly_bulk_generate($request) {
if (! altly_verify_rest_nonce()) {
return new WP_Error('rest_forbidden', __('Nonce verification failed.', 'altly'), array('status' => 403));
}
$license_key = get_option('altly_license_key', '');
if (empty($license_key)) {
return new WP_Error('no_license', 'No license key found', array('status' => 400));
}
// Query images missing alt text.
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => '_wp_attachment_image_alt',
'compare' => 'NOT EXISTS',
),
),
);
$query = new WP_Query($args);
$images = $query->posts;
$results = array();
foreach ($images as $image) {
$file_path = get_attached_file($image->ID);
$filetype = wp_check_filetype($file_path);
$allowed_types = array('image/jpeg', 'image/png', 'image/jpg');
if (! in_array($filetype['type'], $allowed_types, true)) {
$results[] = array('id' => $image->ID, 'status' => 'skipped', 'reason' => 'Unsupported file type');
continue;
}
if (filesize($file_path) > 4 * 1024 * 1024) {
$results[] = array('id' => $image->ID, 'status' => 'skipped', 'reason' => 'File size exceeds 4MB limit');
continue;
}
// Prepare file for upload.
$file_contents = file_get_contents($file_path);
$filename = basename($file_path);
// Build multipart/form-data body using WordPress helper.
$data = array(
array(
'name' => 'file',
'contents' => $file_contents,
'filename' => $filename,
'headers' => array('Content-Type' => $filetype['type']),
),
array(
'name' => 'platform_id',
'contents' => get_bloginfo('name'),
),
array(
'name' => 'platform_url',
'contents' => home_url(),
),
);
$boundary = wp_generate_password(24, false);
$body = wp_http_build_multi_part_body($data, $boundary);
$headers = array(
'Content-Type' => 'multipart/form-data; boundary=' . $boundary,
'Authorization' => 'Bearer ' . $license_key,
);
$args_post = array(
'method' => 'POST',
'timeout' => 15,
'headers' => $headers,
'body' => $body,
);
$response = wp_remote_post(ALTLY_API_QUEUE_URL, $args_post);
if (is_wp_error($response)) {
$results[] = array('id' => $image->ID, 'status' => 'failed', 'reason' => $response->get_error_message());
} else {
$response_body = wp_remote_retrieve_body($response);
$response_data = json_decode($response_body, true);
if (isset($response_data['success']) && $response_data['success'] === true) {
$results[] = array('id' => $image->ID, 'status' => 'queued', 'message' => $response_data['message']);
} else {
$results[] = array('id' => $image->ID, 'status' => 'failed', 'reason' => isset($response_data['error']) ? $response_data['error'] : 'Unknown error');
}
}
}
return rest_ensure_response($results);
}
if (! function_exists('wp_http_build_multi_part_body')) {
/**
* Build a multipart/form-data body.
*
* @param array $data Array of form-data fields.
* @param string $boundary Boundary string.
* @param string $eol End-of-line sequence.
* @return string
*/
function wp_http_build_multi_part_body($data, $boundary, $eol = "\r\n") {
$body = '';
foreach ($data as $part) {
$body .= '--' . $boundary . $eol;
$body .= 'Content-Disposition: form-data; name="' . $part['name'] . '"';
if (! empty($part['filename'])) {
$body .= '; filename="' . $part['filename'] . '"';
}
$body .= $eol;
if (! empty($part['headers']) && is_array($part['headers'])) {
foreach ($part['headers'] as $header => $value) {
$body .= $header . ': ' . $value . $eol;
}
}
$body .= $eol;
$body .= $part['contents'] . $eol;
}
$body .= '--' . $boundary . '--' . $eol;
return $body;
}
}
function altly_queue_image_after_resize($metadata, $attachment_id) {
// Only proceed for supported image types.
$mime_type = get_post_mime_type($attachment_id);
$allowed_types = array('image/jpeg', 'image/png', 'image/jpg');
if (! in_array($mime_type, $allowed_types, true)) {
return $metadata;
}
// Check if this attachment has already been queued.
if (get_post_meta($attachment_id, '_altly_queued', true)) {
return $metadata;
}
$file_path = get_attached_file($attachment_id);
if (! file_exists($file_path)) {
return $metadata;
}
$max_size = 4 * 1024 * 1024; // 4MB limit.
$file_size = filesize($file_path);
// If the original image is too large, attempt to use the medium size.
if ($file_size > $max_size) {
if (isset($metadata['sizes']['medium'])) {
$upload_dir = wp_upload_dir();
$resized_path = trailingslashit($upload_dir['basedir']) . dirname($metadata['file']) . '/' . $metadata['sizes']['medium']['file'];
if (file_exists($resized_path)) {
$resized_size = filesize($resized_path);
if ($resized_size <= $max_size) {
$file_path = $resized_path;
} else {
return $metadata;
}
} else {
return $metadata;
}
} else {
return $metadata;
}
}
// Mark the image as queued to avoid duplicate processing.
update_post_meta($attachment_id, '_altly_queued', true);
// Get the API license key.
$license_key = get_option('altly_license_key', '');
if (empty($license_key)) {
return $metadata;
}
// Build the payload data.
$file_contents = file_get_contents($file_path);
$filename = basename($file_path);
$filetype = wp_check_filetype($file_path);
$image_url = wp_get_attachment_url($attachment_id);
// Prepare the multipart form data.
$data = array(
array(
'name' => 'file',
'contents' => $file_contents,
'filename' => $filename,
'headers' => array('Content-Type' => $filetype['type']),
),
array(
'name' => 'api_key',
'contents' => $license_key,
),
array(
'name' => 'user_id',
'contents' => get_option('altly_user_id', ''),
),
array(
'name' => 'image_id',
'contents' => $attachment_id,
),
array(
'name' => 'image_url',
'contents' => $image_url,
),
array(
'name' => 'platform_id',
'contents' => 'Sandbox',
),
array(
'name' => 'platform_url',
'contents' => home_url(),
),
);
$boundary = wp_generate_password(24, false);
$body = wp_http_build_multi_part_body($data, $boundary);
$headers = array(
'Content-Type' => 'multipart/form-data; boundary=' . $boundary,
'Authorization' => 'Bearer ' . $license_key,
);
$args_post = array(
'method' => 'POST',
'timeout' => 15,
'headers' => $headers,
'body' => $body,
);
wp_remote_post(ALTLY_API_QUEUE_URL, $args_post);
return $metadata;
}
add_filter('wp_generate_attachment_metadata', 'altly_queue_image_after_resize', 10, 2);
function altly_update_frontend_image_alt($attr, $attachment, $size) {
if (empty($attr['alt'])) {
$alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
if (! empty($alt)) {
$attr['alt'] = $alt;
}
}
return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'altly_update_frontend_image_alt', 10, 3);
function altly_update_image_block_alt($block_content, $block) {
// Target only core/image blocks.
if (isset($block['blockName']) && 'core/image' === $block['blockName']) {
// Ensure the block has an image ID.
if (! empty($block['attrs']['id'])) {
$attachment_id = $block['attrs']['id'];
$alt_text = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
if (! empty($alt_text)) {
// Check if an alt attribute exists.
if (preg_match('/alt\s*=\s*"(.*?)"/i', $block_content, $matches)) {
// If the alt attribute exists but is empty, replace it.
if (trim($matches[1]) === '') {
$block_content = preg_replace(
'/alt\s*=\s*""/i',
'alt="' . esc_attr($alt_text) . '"',
$block_content
);
}
} else {
// If no alt attribute is found, insert it into the <img tag.
$block_content = preg_replace(
'/<img(\s)/i',
'<img alt="' . esc_attr($alt_text) . '" $1',
$block_content
);
}
}
}
}
return $block_content;
}
add_filter('render_block', 'altly_update_image_block_alt', 10, 2);