-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathResize-for-discover.php
747 lines (661 loc) · 30.5 KB
/
Resize-for-discover.php
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
<?php
/*
Plugin Name: Resize for discover
Plugin URI:
Description: You can resize images for google discover and AMP⚡ by using this wp plugin.
Text Domain: resize-for-discover
Domain Path: /languages/
Version: 0.0.2
Author: xingxingst
Author URI: https://trade-tech-note.work/
License: GPLv2 or later
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class resizeForDiscover{
const NAME = 'resize-for-discover';
const INITIALCOLOR = '#000000';
public function __construct(){
require_once( __DIR__. '/resizer.php' );
require_once(ABSPATH . 'wp-admin/includes/image.php');
add_action( 'plugins_loaded', array( $this, 'load_lang_strings' ) );
add_action( 'admin_print_footer_scripts', array( $this, 'wpColorPickerScript' ),9);
add_action( 'after_setup_theme', array( $this, 'addFeaturedImageSupport' ), 11 );
add_action( 'after_setup_theme', array( $this, 'add_image_sizes' ), 12 );
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'plugin_action_links' ) );
}
public static function ratios(){
return [
'1:1', '4:3', '16:9',
__('closer 16:9 or 4:3',self::NAME),
__('closer 16:9 or 1:1',self::NAME),
__('closer 4:3 or 1:1',self::NAME),
__('closer 16:9 or 4:3 or 1:1',self::NAME),
__('fixed, to >=1200 x >=1200',self::NAME),
__('fixed, to >=1200 x >=900',self::NAME),
__('fixed, to >=1200 x >=675',self::NAME),
];
}
public static function registerImage($attachment_id, $imagepath){
$attach_data = wp_generate_attachment_metadata( $attachment_id, $imagepath );
wp_update_attachment_metadata( $attachment_id, $attach_data );
}
public static function insertAttachment($imagepath, $id=0){
$filetype = wp_check_filetype( basename( $imagepath ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $imagepath ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $imagepath ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $imagepath, $id );
return $attach_id;
}
/**
* remove backslash etc.
*
* @param [string] $path
* @return string
*/
public static function toWPlocalPath($path){
$pathInfo = ImageResizerForDiscover::mb_pathinfo($path);
return $pathInfo['dirname'] . '/' . $pathInfo['basename'];
}
public function wpColorPickerScript(){
wp_enqueue_script( 'wp-color-picker' );
wp_enqueue_style( 'wp-color-picker' );
}
public function addFeaturedImageSupport(){
global $_wp_theme_features;
if( empty($_wp_theme_features['post-thumbnails']) )
$_wp_theme_features['post-thumbnails'] = array( array('resize-for-discover') );
elseif( true === $_wp_theme_features['post-thumbnails'])
return;
elseif( is_array($_wp_theme_features['post-thumbnails'][0]) )
$_wp_theme_features['post-thumbnails'][0][] = 'resize-for-discover';
}
public function add_image_sizes(){
$saveNewSize = get_option( resizeForDiscoverSettingsPage::OPTION );
if(empty($saveNewSize['field1']['resize-for-discover-newsize']))
return;
$width = 1200;
add_image_size( 'resize_for_discover_hd', $width, 675, true );
add_image_size( 'resize_for_discover_crt', $width, 900, true );
add_image_size( 'resize_for_discover_rect', $width, $width, true );
}
public function load_lang_strings(){
load_plugin_textdomain( self::NAME, false, plugin_basename( dirname( __FILE__ ) ) . '/languages/' );
}
public function plugin_action_links( $links ) {
$url = admin_url( 'admin.php?page=' . resizeForDiscoverSettingsPage::SLUG );
$url = '<a href="' . esc_url( $url ) . '">' . __( 'Settings' ) . '</a>';
array_unshift( $links, $url );
return $links;
}
}
class resizeForDiscoverAttachmentPage{
function __construct(){
add_filter( 'attachment_fields_to_edit',array( $this, 'add_attachment_color_field' ), 10, 2 );
add_filter( 'attachment_fields_to_edit',array( $this, 'add_attachment_overwrite_field' ), 10, 2 );
add_filter( 'attachment_fields_to_edit',array( $this, 'add_attachment_resize_field' ), 10, 2 );
add_action( 'edit_attachment', array( $this, 'save_attachment_resize' ) );
add_action( 'admin_head', array( $this,'admin_media_custom_head'));
add_action( 'admin_print_footer_scripts', array( $this, 'resizeBackgroundColorScript' ), 99999);
}
function admin_media_custom_head() {
?>
<style type="text/css">
.compat-field-resize-for-discover-background td.field{width: 100%;}
</style>
<?php
}
function resizeBackgroundColorScript(){
?>
<script>
jQuery(function ($) {
// Extend wpColorPicker to trigger change on close.
$.widget('custom.myColorPicker', $.wp.wpColorPicker, {
close: function () {
this.element.hide();
if ( this.element.iris( 'instance' ) ) {
this.element.iris( 'toggle' );
}
this.button.addClass( 'hidden' );
this.toggler.removeClass( 'wp-picker-open' );
$( 'body' ).off( 'click.wpcolorpicker', this.close );
if (this.initialValue !== this.element.val()) {
this.element.change();
}
}
});
});
</script>
<?php
}
function getInitialColor(){
$saveColor = get_option( resizeForDiscoverSettingsPage::OPTION );
return empty($saveColor['field1']['resize-for-discover-background'])
? resizeForDiscover::INITIALCOLOR
: $saveColor['field1']['resize-for-discover-background'];
}
function getFileType($post){
$imagepath= get_attached_file($post->ID);
$type = wp_check_filetype($imagepath);
return $type['ext'];
}
function isImage($type){
return $type === 'png' || $type === 'jpg'
|| $type === 'jpeg' || $type === 'gif';
}
function add_attachment_color_field( $form_fields, $post ) {
$filetype = $this->getFileType($post);
if(!$this->isImage($filetype)) return $form_fields;
$field_value = get_post_meta( $post->ID, 'resize-for-discover-background', true );
$savedColor = $this->getInitialColor();
$viewColor = $field_value ? $field_value : $savedColor;
$transparentBool = $field_value === 'transparent';
$form_fields['resize-for-discover-background'] = array(
'input' => 'text',
'value' => $transparentBool ? '' : esc_attr($viewColor),
'label' => __( 'Background color for resize',resizeForDiscover::NAME),
);
ob_start();
?>
<script>
let existSaveWaiting = function (records){
// search past 'save-waiting' class
let len = records.length;
let exist = false;
for( let i=0; i<len; i++) {
if(records[i].oldValue.indexOf('save-waiting') > 0){
exist = true;
break;
}
}
return exist;
}
let mediaReloader = function (){
// get wp outside iframe
var wp = parent.wp;
// switch tabs (required for the code below)
wp.media.frame.setState('insert');
// refresh
if( wp.media.frame.content.get() !== null) {
wp.media.frame.content.get().collection.props.set({ignore: (+ new Date())});
wp.media.frame.content.get().options.selection.reset();
} else {
wp.media.frame.library.props.set ({ignore: (+ new Date())});
}
}
let autoReload = function (records){
if(!existSaveWaiting(records)){
jQuery('.resize-for-discover-spinner').addClass('save-waiting');
return;
}
mediaReloader();
};
jQuery(function($){
let nowPage = location.href.indexOf('upload.php');
let reloderElm = $('.resize-for-discover-reloader');
$('[name$="[resize-for-discover-background]"]').myColorPicker();
if(nowPage > 0){
reloderElm.hide();
$('.reloader-help').hide();
}else{
reloderElm.on('click',mediaReloader);
}
//reload attachment page
$('.resize-for-discover-select').change(function(){
let reloadFlg = false;
let observer;
let modal;
if(nowPage == -1 && $('.media-sidebar').length>0){
reloadFlg = true;
modals = document.getElementsByClassName('media-sidebar');
let length = modals.length;
for (let index = 0; index < length; index++) {
modal = modals[index].querySelector('.attachment-details');
if(modal){
break;
}
}
observer = new MutationObserver(function(records){autoReload(records)});
}else if(nowPage > 0 && $('.edit-attachment-frame').length>0){
reloadFlg = true;
modal = document.getElementsByClassName('edit-attachment-frame')[0].querySelector('.attachment-details');
observer = new MutationObserver(function(records){
if(!existSaveWaiting(records)){return;}
location.reload();
});
}
if(reloadFlg){
if(modal){
observer.observe(modal, {
attributes: true,
attributeOldValue :true,
attributeFilter: ['class']
});
}else{
console.warn('This window cannnot be reloaded.');
}
}
});
});
</script>
<?php
$text_color_js = ob_get_clean();
$form_fields['text_color_js'] = array(
'tr' => $text_color_js, // Adds free-form stuff to table.
);
//for transparent checkbox
if($filetype === 'png' || $filetype === 'gif'){
$saveTransparent = get_option( resizeForDiscoverSettingsPage::OPTION );
$saveTransparent = empty($saveTransparent['field1']['resize-for-discover-transparent']) ? '' : 'transparent';
$field_value = $field_value === '' ? $saveTransparent : $field_value;
$form_fields['resize-for-discover-transparent'] = array(
'input' => 'html',
'html' => $this->fieldCheckboxHTML(
$post->ID,
'resize-for-discover-transparent',
'transparent',
$field_value,
__('Transparent', resizeForDiscover::NAME)
),
'helps' => __('If you fill the checkbox, This setting takes priority.',resizeForDiscover::NAME),
'value' => 'transparent',
'label' => '',
);
}else{
$form_fields['resize-for-discover-transparent'] = array('input' => 'hidden', 'value' => '');
}
return $form_fields;
}
function add_attachment_overwrite_field( $form_fields, $post ) {
$filetype = $this->getFileType($post);
if(!$this->isImage($filetype)) return $form_fields;
$field_value = get_post_meta( $post->ID, 'resize-for-discover-overwrite', true );
$saveOverwrite = get_option( resizeForDiscoverSettingsPage::OPTION );
$saveOverwrite = empty($saveOverwrite['field1']['resize-for-discover-overwrite']) ? 0 : 1;
$field_value = $field_value === '' ? $saveOverwrite : $field_value;
$form_fields['resize-for-discover-overwrite'] = array(
'input' => 'html',
'html' => $this->fieldCheckboxHTML($post->ID, 'resize-for-discover-overwrite', 1, $field_value, ''),
// 'value' => 'transparent',
'label' => __('Overwrite',resizeForDiscover::NAME),
);
return $form_fields;
}
function fieldCheckboxHTML( $postID, $index, $value, $field_value, $text) {
$label = esc_attr($index .'-'. $postID);
$checked = $field_value== $value ? " checked='checked'" : '';
$nameAttr = esc_attr("attachments[{$postID}][{$index}]");
$value = esc_attr($value);
$result = "<label for='{$label}'>
<input type='checkbox' id='{$label}' name='{$nameAttr}' value='{$value}'{$checked}
/> {$text}
</label>";
return $result;
}
function add_attachment_resize_field( $form_fields, $post ) {
$filetype = $this->getFileType($post);
if(!$this->isImage($filetype)) return $form_fields;
$field_value = get_post_meta( $post->ID, 'resize-for-discover', true );
$form_fields['resize-for-discover'] = array(
'input' => 'html',
'label' => __( 'Raito', resizeForDiscover::NAME),
);
$form_fields['resize-for-discover']['html']
= "<select class='resize-for-discover-select' name='attachments[{$post->ID}][resize-for-discover]' id='attachments[{$post->ID}][resize-for-discover]' style='font-size:1em;'>\n";
$field_value = $field_value === "" ? '-1' : $field_value;
$form_fields['resize-for-discover']['html']
.="<option value='-1'>".__('select', resizeForDiscover::NAME)."</option>\n";
foreach(resizeForDiscover::ratios() as $key => $value){
$selected = (int)$field_value === $key ? 'selected' : '';
$key = esc_attr($key);
$text = $value;
$form_fields['resize-for-discover']['html'] .= "<option value='{$key}' {$selected}>{$text}</option>\n";
}
$form_fields['resize-for-discover']['html'].="</select>\n";
$form_fields['resize-for-discover']['html'].=
'<p class="help">' . __( 'If this width is shorter than 1200px or pixel is smaller than 800000 pixel,the picture will be resized to this conditions.',resizeForDiscover::NAME) . '</p>';
$style =
'position: initial; overflow: initial; top: initial; bottom: initial; right: initial; left: initial; box-shadow: initial;';
$form_fields['resize-for-discover']['html'] .=
'<span class="attachment-details resize-for-discover-spinner" style="'. esc_html($style) . '">
<span class="settings-save-status" role="status">
<span class="spinner"></span>
<span class="saved">'. esc_html__( 'Saved.') .'</span>
</span>
</span>';
$form_fields['resize-for-discover']['html'] .=
'<button class="resize-for-discover-reloader button" type="button">'.
__( 'Reload window', resizeForDiscover::NAME) .
'</button>';
$form_fields['resize-for-discover']['html'].=
'<p class="help reloader-help">' .
__( 'Press this button when you select the above ratio but the screen does not reload.',resizeForDiscover::NAME) .
'</p>';
return $form_fields;
}
function save_attachment_resize( $attachment_id ) {
$color= '';
if(isset($_REQUEST['attachments'][$attachment_id])
&& is_array($_REQUEST['attachments'][$attachment_id])){
$values = array_map( 'esc_attr', $_REQUEST['attachments'][$attachment_id] );;
}else{
return;
}
if(!empty($values['resize-for-discover-transparent'])){
$color =$values['resize-for-discover-transparent'];
}elseif (!empty( $values['resize-for-discover-background'])) {
$color = $values['resize-for-discover-background'];
}else{
$color = $this->getInitialColor();
}
update_post_meta( $attachment_id, 'resize-for-discover-background', $color );
$overwrite = empty($values['resize-for-discover-overwrite'] ) ? 0 : 1;
update_post_meta( $attachment_id, 'resize-for-discover-overwrite', $overwrite );
if ( isset( $values['resize-for-discover'] )) {
$mode = $values['resize-for-discover'];
if(!isset($mode) || $mode === "") return;
update_post_meta( $attachment_id, 'resize-for-discover', $mode );
if($mode === "-1") return;
$imagepath = get_attached_file($attachment_id);
$color = empty($color) ? get_post_meta($attachment_id, 'resize-for-discover-background', true ) : $color;
$resizeIns = new ImageResizerForDiscover($imagepath,$overwrite, $color);
if(!$overwrite)
$resizeIns->setSuffix('-'. ltrim($color,'#') . '-' . $mode);
//重複を防ぐ
$resizeIns->setSavePath();
if(file_exists($resizeIns->getSavePath())) return;
try {
$saveResult = $resizeIns ->resizeForDiscover($mode, true);
if($saveResult){
$imagepath = $resizeIns->getSavePath();
$imagepath = resizeForDiscover::toWPlocalPath($imagepath);
if(!$overwrite) {
update_post_meta( $attachment_id, 'resize-for-discover', -1 );
$attachment_id = resizeForDiscover::insertAttachment($imagepath);
update_post_meta( $attachment_id, 'resize-for-discover-background', $color );
update_post_meta( $attachment_id, 'resize-for-discover', $mode );
}
resizeForDiscover::registerImage($attachment_id, $imagepath);
}
} catch (Exception $th) {
error_log(print_r($th->getMessage(),true));
}
}
}
}
class resizeForDiscoverSettingsPage
{
private $options;
const SLUG = 'resize-thumbnail-discover-settings';
const OPTION = 'resize_thumbnail_discover_options';
public function __construct() {
add_action( 'admin_menu', array( $this, 'add_menu' ) );
add_action( 'admin_init', array( $this, 'init_page' ) );
}
function add_menu() {
add_options_page( 'Resize For Discover Settings', 'Resize For Discover', 'manage_options', self::SLUG, array( $this, 'create_page' ) );
}
function getActiveTab(){
if(isset( $_GET['tab'] )){
$active_tab = strval($_GET['tab']);
if( $active_tab === 'tab-page1'){
return 'tab-page1';
}elseif ($active_tab === 'tab-page2') {
return 'tab-page2';
}
}
return 'tab-page1';
}
function create_page() {
?>
<div class="wrap">
<h1><?php _e("Resize For Discover Settings", resizeForDiscover::NAME); ?></h1>
<?php $active_tab = $this->getActiveTab(); ?>
<h2 class="nav-tab-wrapper">
<a href="?page=<?=esc_attr(self::SLUG)?>&tab=tab-page1" class="nav-tab <?php echo $active_tab == 'tab-page1' ? 'nav-tab-active' : ''; ?>"><?php _e("Initial setting", resizeForDiscover::NAME); ?></a>
<a href="?page=<?=esc_attr(self::SLUG)?>&tab=tab-page2" class="nav-tab <?php echo $active_tab == 'tab-page2' ? 'nav-tab-active' : ''; ?>"><?php _e("Resize post thumbnails", resizeForDiscover::NAME); ?></a>
</h2>
<form method="post" action="options.php">
<?php
settings_fields( 'resize_for_discover_settings' );
do_settings_sections( self::SLUG );
submit_button();
?>
</form>
</div>
<?php
}
function init_page() {
$this->options = get_option( self::OPTION );
$active_tab = $this->getActiveTab();
switch ( $active_tab ){
case 'tab-page1':
add_settings_section( 'resize_for_discover_section1', __("Initial setting", resizeForDiscover::NAME), '__return_false', self::SLUG);
add_settings_field( 'field1', '', array( $this, 'display_field1' ), self::SLUG, 'resize_for_discover_section1' , array('field'=>'field1'));
break;
case 'tab-page2':
add_settings_section( 'resize_for_discover_section2', __('Resize and register all post thumbail', resizeForDiscover::NAME), '__return_false', self::SLUG );
add_settings_field( 'field2', '', array( $this, 'display_field2' ), self::SLUG, 'resize_for_discover_section2' );
break;
}
register_setting( 'resize_for_discover_settings' , self::OPTION, array( $this, 'sanitize' ) );
}
function sanitize( $input ) {
$output = get_option( self::OPTION );
if ( isset( $input['field1'] ) ){
$output['field1']['resize-for-discover-background'] =
sanitize_hex_color($input['field1']['resize-for-discover-background']);
$output['field1']['resize-for-discover-transparent'] =
empty($input['field1']['resize-for-discover-transparent']) && $input['field1']['resize-for-discover-transparent'] !== 'transparent'
? '' : 'transparent';
$output['field1']['resize-for-discover-overwrite'] =
empty($input['field1']['resize-for-discover-overwrite'])
? 0 : 1;
$output['field1']['resize-for-discover-newsize'] =
empty($input['field1']['resize-for-discover-newsize'])
? 0 : 1;
}
if ( isset( $input['field2'] ) ){
if(isset( $input['field2']['all']) === !empty($input['field2']['ids'])){
add_settings_error( self::SLUG, 'message', __('Either check all resize or Input Post IDs.'));
return $output;
}
$postIDs = isset($input['field2']['all']) ? array_column(get_posts(), 'ID') :
explode(",", sanitize_text_field($input['field2']['ids'])) ;
$color = empty($input['field2']['resize-for-discover-background'])
? resizeForDiscover::INITIALCOLOR
: sanitize_hex_color($input['field2']['resize-for-discover-background']);
$transparent =
empty($input['field2']['transparent']) && $input['field1']['transparent'] !== 'transparent'
? '' : 'transparent';
$mode = (int)$input['field2']['ratio'];
if($mode < 0 || $mode > 9){
add_settings_error( self::SLUG, 'message', __('Invalid ratio value.'));
return $output;
}
$this->resizeAndInsertThumbFromID($mode, $postIDs, $color, $transparent);
}
return $output;
}
function resizeAndInsertThumbFromID($mode, $postIDs, $color, $transparent){
$resizedImage=[];
$error = '';
$updateFlg = false;
foreach ($postIDs as $id) {
$thumbID = get_post_thumbnail_id($id);
if(!$thumbID){
$error .= 'Post ID ' . $id . __(' does not have eyecatch or does not exist.') . "<br>\n";
continue;
}
if(isset($resizedImage[$thumbID])) continue; //same image isn't resized.
$imagepath= get_attached_file($thumbID);
$type = wp_check_filetype($imagepath);
$applyColor = $transparent && $type['ext'] === 'png'
? $transparent : $color;
$resizeIns = new ImageResizerForDiscover($imagepath, false, $applyColor);
try {
// throw new Exception('exception'); //for messege check
$saveResult = $resizeIns ->resizeForDiscover($mode);
if($saveResult){
$imagepath = $resizeIns->getSavePath();
$imagepath = resizeForDiscover::toWPlocalPath($imagepath);
$attach_id = resizeForDiscover::insertAttachment($imagepath, $id);
if($attach_id) {
resizeForDiscover::registerImage($attach_id, $imagepath);
set_post_thumbnail( $id, $attach_id );
$resizedImage[$thumbID] = true;
}
$updateFlg = true;
}else{
$error .= 'Post ID '. $id .__("'s eyecactch is not resized. Because This image is too big.<br>\n");
}
} catch (Exception $th) {
$errorString = $th->getMessage();
error_log(print_r($errorString,true));
$error .= "Post ID {$id} error:{$errorString} <br> \n";
}
}
if(!empty($error)){
$type = $updateFlg ? 'updated' : 'error';
add_settings_error( self::SLUG, 'message', $error, $type);
}
}
function ratioListSelect($name,$checkedRatio=0){
?>
<select name="<?= esc_attr($name) ?>" >
<?php
foreach (resizeForDiscover::ratios() as $val => $txt) {
?>
<option value="<?=esc_attr($val) ?>"
<?= $checkedRatio == $val ? esc_attr('selected') : esc_attr('') ?>>
<?= $txt ?>
</label>
<?php
}
?>
</select>
<?php
}
function input_color($array){
$color = empty($this->options) || empty($this->options['field1']['resize-for-discover-background'])
? resizeForDiscover::INITIALCOLOR
: $this->options['field1']['resize-for-discover-background'];
?>
<th scope="row"><?php _e('Letter box color', resizeForDiscover::NAME); ?></th>
<td>
<input type="text" name="<?=esc_attr( self::OPTION . '[' . $array['field'] )?>][resize-for-discover-background]" value="<?= esc_attr($color) ?>">
</td>
<script>
jQuery(document).ready(function($){
$('[name$="[resize-for-discover-background]"]').wpColorPicker();
});
</script>
<?php
}
function checkbox_transparent($array){
$transparentChecked = empty($this->options)
|| empty($this->options['field1']['resize-for-discover-transparent'])
? '' : ' checked="checked"';
?>
<th scope="row"><label for="transparent"><?php _e('Transparent', resizeForDiscover::NAME); ?></label></th>
<td>
<input id="transparent" type="checkbox" name="<?= esc_attr(self::OPTION . '[' . $array['field'] )?>][resize-for-discover-transparent]" value="transparent"<?= esc_attr($transparentChecked) ?>>
</td>
<?php
}
function checkbox_overwrite($array){
$overwriteChecked = empty($this->options)
|| empty($this->options['field1']['resize-for-discover-overwrite'])
? '' : ' checked="checked"';
?>
<th scope="row"><label for="overwrite"><?php _e('Overwrite', resizeForDiscover::NAME); ?></label></th>
<td>
<input id="overwrite" type="checkbox" name="<?= esc_attr(self::OPTION . '[' . $array['field']) ?>][resize-for-discover-overwrite]" value="1"<?=esc_attr($overwriteChecked) ?>>
</td>
<?php
}
function display_field1($array) {
$newSizeChecked = empty($this->options)
|| empty($this->options['field1']['resize-for-discover-newsize'])
? '' : ' checked="checked"';
?>
<div style="margin-left: -200px;">
<table>
<tr>
<?php $this->input_color($array); ?>
</tr>
<tr>
<?php $this->checkbox_transparent($array); ?>
</tr>
<tr>
<?php $this->checkbox_overwrite($array); ?>
</tr>
<tr>
<th scope="row"><label for="new-image-size"><?php _e('Register new Image Size', resizeForDiscover::NAME); ?></label></th>
<td>
<div style="margin-bottom: 1em;"><input id="new-image-size" type="checkbox" name="<?= self::OPTION ?>[field1][resize-for-discover-newsize]" value="1"<?= esc_attr($newSizeChecked) ?>></div>
<div>
<p><?php _e('Registers Below new Image Size.', resizeForDiscover::NAME); ?></p>
<p>
<?php _e('1200 x 675', resizeForDiscover::NAME); ?><br>
<?php _e('1200 x 900', resizeForDiscover::NAME); ?><br>
<?php _e('1200 x 1200', resizeForDiscover::NAME); ?>
</p>
</div>
</td>
</tr>
</table>
</div>
<?php
}
function display_field2() {
$indexArray = ['field'=>'field2'];
?>
<div style="margin-left: -200px;">
<p><?php _e("Resize images that are less than 1200px wide or less than 800000px.", resizeForDiscover::NAME); ?>
<table>
<tr>
<th scope="row"><?php _e('ratio', resizeForDiscover::NAME); ?></th>
<td>
<?php $this->ratioListSelect(self::OPTION . '[field2][ratio]'); ?>
</td>
</tr>
<tr>
<?php $this->input_color($indexArray); ?>
</tr>
<tr>
<?php $this->checkbox_transparent($indexArray); ?>
</tr>
<!-- <tr> If there is demand -->
<?php // $this->checkbox_overwrite($indexArray); ?>
<!-- </tr> -->
<tr>
<th scope="row"><label for="all-resize"><?php _e('Resize and register all post thumbnails', resizeForDiscover::NAME); ?></label></th>
<td>
<input type="checkbox" id="all-resize" name="<?= esc_attr(self::OPTION) ?>[field2][all]" value="1">
</td>
</tr>
<tr>
<th scope="row"><label for="resize-post-id"><?php _e("Post ID", resizeForDiscover::NAME); ?></label></th>
<td>
<input type="text" pattern="^[0-9,]+$" id="resize-post-id" name="<?= esc_attr(self::OPTION) ?>[field2][ids]"><br>
<p><?php _e("Input post IDs with thumbnail you want to resize, <br> separated by commas.", resizeForDiscover::NAME); ?></p>
</td>
</tr>
</table>
</div>
<?php
}
}
if( is_admin() ) {
new resizeForDiscover();
new resizeForDiscoverAttachmentPage();
new resizeForDiscoverSettingsPage();
}