-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreads-auto-poster.php
More file actions
3306 lines (2776 loc) · 151 KB
/
threads-auto-poster.php
File metadata and controls
3306 lines (2776 loc) · 151 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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: WordPress to Threads & X
* Plugin URI: https://extroverteddeveloper.com
* Description: Automatically posts WordPress blog posts to Meta's Threads platform and X (Twitter) with intelligent character limit handling and URL shortening.
* Version: 2.0.0
* Author: ExtrovertedDeveloper
* License: MIT
* Text Domain: threads-auto-poster
*/
if (!defined('ABSPATH')) {
exit;
}
define('WORDPRESS_TO_THREADS_VERSION', '2.0.0');
define('WORDPRESS_TO_THREADS_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('WORDPRESS_TO_THREADS_PLUGIN_URL', plugin_dir_url(__FILE__));
// Load the autoshare-for-twitter library if available
if (file_exists(WP_PLUGIN_DIR . '/autoshare-for-twitter/vendor/autoload.php')) {
require_once WP_PLUGIN_DIR . '/autoshare-for-twitter/vendor/autoload.php';
}
class ThreadsAutoPoster {
private static $instance = null;
private $threads_character_limit = 500;
private $x_character_limit = 280;
private $x_url_length = 23; // X counts all URLs as 23 characters
public static function get_instance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_action('init', array($this, 'init'));
register_activation_hook(__FILE__, array($this, 'activate'));
register_deactivation_hook(__FILE__, array($this, 'deactivate'));
}
public function init() {
add_action('publish_post', array($this, 'auto_post_to_threads'), 10, 2);
$this->handle_oauth_endpoints();
$this->handle_x_oauth_endpoints();
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_init', array($this, 'admin_init'));
add_action('wp_ajax_threads_store_publish_choice', array($this, 'handle_store_publish_choice'));
add_action('wp_ajax_threads_retry_all_pending', array($this, 'handle_retry_all_pending'));
add_action('wp_ajax_threads_retry_single_pending', array($this, 'handle_retry_single_pending'));
add_action('wp_ajax_threads_wizard_save', array($this, 'handle_wizard_save'));
add_action('wp_ajax_threads_wizard_set_oauth_return', array($this, 'handle_wizard_set_oauth_return'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
add_action('threads_refresh_token', array($this, 'refresh_access_token'));
add_action('admin_notices', array($this, 'show_authorization_notices'));
// X OAuth callback handlers using admin-post.php
add_action('admin_post_x_oauth_callback', array($this, 'handle_x_oauth_callback'));
add_action('admin_post_nopriv_x_oauth_callback', array($this, 'handle_x_oauth_callback'));
// Scheduled posting cron hooks
add_action('threads_scheduled_post_to_threads', array($this, 'scheduled_post_to_threads'), 10, 2);
add_action('threads_scheduled_post_to_x', array($this, 'scheduled_post_to_x'), 10, 1);
// Add Threads status column to posts list
add_filter('manage_post_posts_columns', array($this, 'add_threads_status_column'));
add_action('manage_post_posts_custom_column', array($this, 'display_threads_status_column'), 10, 2);
// Add bulk actions for posting to Threads
add_filter('bulk_actions-edit-post', array($this, 'add_bulk_actions'));
add_filter('handle_bulk_actions-edit-post', array($this, 'handle_bulk_actions'), 10, 3);
add_action('admin_notices', array($this, 'bulk_action_admin_notice'));
// Ensure cron job is scheduled if we have tokens
$this->ensure_token_refresh_scheduled();
}
public function activate() {
add_option('threads_app_id', '');
add_option('threads_app_secret', '');
add_option('threads_user_id', '');
add_option('threads_access_token', '');
add_option('bitly_access_token', '');
add_option('threads_auto_post_enabled', '1');
add_option('threads_include_media', '1');
add_option('threads_media_priority', 'featured');
add_option('threads_token_expires', '');
add_option('threads_enable_thread_chains', '1');
add_option('threads_attribution_reply_enabled', '1');
add_option('threads_max_chain_length', '5');
add_option('threads_split_preference', 'sentences');
// X (Twitter) options
add_option('x_auto_post_enabled', '0');
add_option('x_api_key', '');
add_option('x_api_secret', '');
add_option('x_access_token', '');
add_option('x_access_token_secret', '');
add_option('x_include_media', '1');
if (!wp_next_scheduled('threads_refresh_token')) {
// Schedule every 12 hours (43200 seconds) starting now
wp_schedule_event(time(), 'twicedaily', 'threads_refresh_token');
}
// Setup wizard option
add_option('threads_setup_complete', '0');
// Trigger redirect to setup wizard on activation
set_transient('threads_activation_redirect', true, 30);
// Add custom 12-hour interval if it doesn't exist
add_filter('cron_schedules', array($this, 'add_custom_cron_intervals'));
flush_rewrite_rules();
}
public function deactivate() {
wp_clear_scheduled_hook('threads_refresh_token');
}
public function add_custom_cron_intervals($schedules) {
$schedules['thirty_minutes'] = array(
'interval' => 30 * MINUTE_IN_SECONDS,
'display' => __('Every 30 Minutes')
);
return $schedules;
}
public function add_admin_menu() {
add_options_page(
'WordPress to Threads & X Settings',
'Threads & X',
'manage_options',
'wordpress-to-threads',
array($this, 'admin_page')
);
// Hidden setup wizard page (registered under Settings, then removed from menu)
add_submenu_page(
'options-general.php',
'WordPress to Threads & X Setup',
'Setup Wizard',
'manage_options',
'wordpress-to-threads-setup',
array($this, 'setup_wizard_page')
);
remove_submenu_page('options-general.php', 'wordpress-to-threads-setup');
}
public function admin_init() {
// Redirect to setup wizard on first activation
if (get_transient('threads_activation_redirect')) {
delete_transient('threads_activation_redirect');
$is_wizard_page = isset($_GET['page']) && $_GET['page'] === 'wordpress-to-threads-setup';
if (!isset($_GET['activate-multi']) && !$is_wizard_page && get_option('threads_setup_complete', '1') !== '1') {
wp_safe_redirect(admin_url('options-general.php?page=wordpress-to-threads-setup'));
exit;
}
}
register_setting('wordpress_to_threads_settings', 'threads_app_id');
register_setting('wordpress_to_threads_settings', 'threads_app_secret');
register_setting('wordpress_to_threads_settings', 'bitly_access_token');
register_setting('wordpress_to_threads_settings', 'threads_auto_post_enabled');
register_setting('wordpress_to_threads_settings', 'threads_include_media');
register_setting('wordpress_to_threads_settings', 'threads_media_priority');
register_setting('wordpress_to_threads_settings', 'threads_enable_thread_chains');
register_setting('wordpress_to_threads_settings', 'threads_max_chain_length');
register_setting('wordpress_to_threads_settings', 'threads_split_preference');
register_setting('wordpress_to_threads_settings', 'threads_attribution_reply_enabled');
// X (Twitter) settings
register_setting('wordpress_to_threads_settings', 'x_auto_post_enabled');
register_setting('wordpress_to_threads_settings', 'x_api_key');
register_setting('wordpress_to_threads_settings', 'x_api_secret');
register_setting('wordpress_to_threads_settings', 'x_include_media');
// Note: x_access_token, x_access_token_secret, x_username, x_user_id
// are NOT registered here because they're set via OAuth flow, not form submission
// Bulk posting settings
register_setting('wordpress_to_threads_settings', 'bulk_post_stagger_interval');
}
public function admin_page() {
?>
<div class="wrap">
<h1>WordPress to Threads & X Settings</h1>
<p><a href="<?php echo esc_url(admin_url('options-general.php?page=wordpress-to-threads-setup')); ?>" class="button button-secondary">Run Setup Wizard</a> <span style="margin-left: 8px; color: #646970;">Step-by-step guided setup with instructions</span></p>
<form method="post" action="options.php">
<?php
settings_fields('wordpress_to_threads_settings');
do_settings_sections('wordpress_to_threads_settings');
?>
<h2>Threads Settings</h2>
<table class="form-table">
<tr>
<th scope="row">Enable Auto Posting to Threads</th>
<td>
<input type="checkbox" name="threads_auto_post_enabled" value="1" <?php checked(get_option('threads_auto_post_enabled'), '1'); ?> />
<p class="description">Enable automatic posting to Threads when a blog post is published.</p>
</td>
</tr>
<tr>
<th scope="row">Threads App ID</th>
<td>
<input type="password" name="threads_app_id" value="<?php echo esc_attr(get_option('threads_app_id')); ?>" class="regular-text" />
<button type="button" class="button button-small threads-toggle-visibility">Show</button>
<p class="description">Your Threads App ID from Meta for Developers.</p>
</td>
</tr>
<tr>
<th scope="row">Threads App Secret</th>
<td>
<input type="password" name="threads_app_secret" value="<?php echo esc_attr(get_option('threads_app_secret')); ?>" class="regular-text" />
<button type="button" class="button button-small threads-toggle-visibility">Show</button>
<p class="description">Your Threads App Secret from Meta for Developers.</p>
</td>
</tr>
<tr>
<th scope="row">Threads User ID</th>
<td>
<div style="padding: 6px 8px; background-color: #f1f1f1; border: 1px solid #ddd; border-radius: 3px; display: inline-block; min-width: 200px;"><?php echo esc_html(get_option('threads_user_id') ?: 'Not set - authorize to retrieve'); ?></div>
<p class="description">Your Threads user ID (retrieved automatically from OAuth).</p>
</td>
</tr>
<tr>
<th scope="row">OAuth Authorization</th>
<td>
<?php
$access_token = get_option('threads_access_token');
$token_expires = get_option('threads_token_expires');
$app_id = get_option('threads_app_id');
$app_secret = get_option('threads_app_secret');
if ($access_token) {
if (!empty($token_expires) && $this->is_token_expired()) {
echo '<span style="color: orange;">⚠ Token expires soon - will auto-refresh</span><br>';
} else {
echo '<span style="color: green;">✓ Authorized</span><br>';
}
echo '<a href="' . $this->get_deauthorize_url() . '" class="button">Deauthorize</a>';
} elseif (empty($app_id) || empty($app_secret)) {
echo '<span style="color: red;">⚠ Please save your App ID and App Secret first</span>';
} else {
// Check if we recently cleared expired credentials
if (!empty($token_expires) && time() > $token_expires) {
echo '<span style="color: red;">⚠ Your token has expired. Please re-authorize.</span><br>';
}
echo '<a href="' . $this->get_authorize_url() . '" class="button button-primary">Authorize with Threads</a>';
}
?>
<p class="description">Authorize this plugin to post to your Threads account.</p>
</td>
</tr>
<tr>
<th scope="row">Bitly Access Token (optional, but recommended)</th>
<td>
<input type="password" name="bitly_access_token" value="<?php echo esc_attr(get_option('bitly_access_token')); ?>" class="regular-text" />
<button type="button" class="button button-small threads-toggle-visibility">Show</button>
<p class="description">Your Bitly API access token for URL shortening.</p>
</td>
</tr>
<tr>
<th scope="row">Include Media</th>
<td>
<input type="checkbox" name="threads_include_media" value="1" <?php checked(get_option('threads_include_media', '1'), '1'); ?> />
<p class="description">Include images and videos from posts when posting to Threads.</p>
</td>
</tr>
<tr>
<th scope="row">Media Priority</th>
<td>
<select name="threads_media_priority">
<option value="featured" <?php selected(get_option('threads_media_priority', 'featured'), 'featured'); ?>>Featured Image First</option>
<option value="content" <?php selected(get_option('threads_media_priority', 'featured'), 'content'); ?>>Content Images First</option>
<option value="video" <?php selected(get_option('threads_media_priority', 'featured'), 'video'); ?>>Videos First</option>
</select>
<p class="description">Choose which media to prioritize when multiple options are available.</p>
</td>
</tr>
<tr>
<th scope="row">Enable Thread Chains</th>
<td>
<input type="checkbox" name="threads_enable_thread_chains" value="1" <?php checked(get_option('threads_enable_thread_chains', '1'), '1'); ?> />
<p class="description">For posts longer than 500 characters, create a series of connected thread posts instead of truncating.</p>
</td>
</tr>
<tr>
<th scope="row">Maximum Thread Chain Length</th>
<td>
<select name="threads_max_chain_length">
<?php
$max_length = get_option('threads_max_chain_length', '5');
for ($i = 2; $i <= 10; $i++) {
echo '<option value="' . $i . '"' . selected($max_length, $i, false) . '>' . $i . ' posts</option>';
}
?>
</select>
<p class="description">Maximum number of posts in a thread chain (including the main post).</p>
</td>
</tr>
<tr>
<th scope="row">Content Splitting Method</th>
<td>
<select name="threads_split_preference">
<option value="sentences" <?php selected(get_option('threads_split_preference', 'sentences'), 'sentences'); ?>>Split at sentence boundaries</option>
<option value="paragraphs" <?php selected(get_option('threads_split_preference', 'sentences'), 'paragraphs'); ?>>Split at paragraph boundaries</option>
<option value="words" <?php selected(get_option('threads_split_preference', 'sentences'), 'words'); ?>>Split at word boundaries</option>
</select>
<p class="description">How to intelligently split long content into thread posts.</p>
</td>
</tr>
<tr>
<th scope="row">Add Attribution Reply</th>
<td>
<input type="checkbox" name="threads_attribution_reply_enabled" value="1" <?php checked(get_option('threads_attribution_reply_enabled', '1'), '1'); ?> />
<p class="description">Append a final reply to every thread crediting the original blog post and linking to the WordpressToThreads plugin.</p>
</td>
</tr>
</table>
<h2>X (Twitter) Settings</h2>
<table class="form-table">
<tr>
<th scope="row">Enable Auto Posting to X</th>
<td>
<input type="checkbox" name="x_auto_post_enabled" value="1" <?php checked(get_option('x_auto_post_enabled'), '1'); ?> />
<p class="description">Enable automatic posting to X (Twitter) when a blog post is published.</p>
</td>
</tr>
<tr>
<th scope="row">X API Key (Consumer Key)</th>
<td>
<input type="password" name="x_api_key" value="<?php echo esc_attr(get_option('x_api_key')); ?>" class="regular-text" />
<button type="button" class="button button-small threads-toggle-visibility">Show</button>
<p class="description">Your X API Key from <a href="https://developer.twitter.com/en/portal/projects-and-apps" target="_blank">X Developer Portal</a>.</p>
</td>
</tr>
<tr>
<th scope="row">X API Secret (Consumer Secret)</th>
<td>
<input type="password" name="x_api_secret" value="<?php echo esc_attr(get_option('x_api_secret')); ?>" class="regular-text" />
<button type="button" class="button button-small threads-toggle-visibility">Show</button>
<p class="description">Your X API Secret from X Developer Portal.</p>
</td>
</tr>
<tr>
<th scope="row">OAuth Authorization</th>
<td>
<?php
$x_access_token = get_option('x_access_token');
$x_api_key = get_option('x_api_key');
$x_api_secret = get_option('x_api_secret');
if ($x_access_token) {
$x_username = get_option('x_username');
echo '<span style="color: green;">✓ Authorized' . ($x_username ? ' as @' . esc_html($x_username) : '') . '</span><br>';
echo '<a href="' . $this->get_x_deauthorize_url() . '" class="button">Deauthorize</a>';
} elseif (empty($x_api_key) || empty($x_api_secret)) {
echo '<span style="color: red;">⚠ Please save your API Key and API Secret first</span>';
} else {
echo '<a href="' . $this->get_x_authorize_url() . '" class="button button-primary">Authorize with X</a>';
}
?>
<p class="description">Authorize this plugin to post to your X account. You must save your API credentials first.</p>
</td>
</tr>
<tr>
<th scope="row">Include Media on X</th>
<td>
<input type="checkbox" name="x_include_media" value="1" <?php checked(get_option('x_include_media', '1'), '1'); ?> />
<p class="description">Include images from posts when posting to X (Twitter).</p>
</td>
</tr>
</table>
<h2>Bulk Posting Settings</h2>
<table class="form-table">
<tr>
<th scope="row">Stagger Bulk Posts</th>
<td>
<select name="bulk_post_stagger_interval">
<option value="0" <?php selected(get_option('bulk_post_stagger_interval', '0'), '0'); ?>>No delay (post immediately)</option>
<option value="1800" <?php selected(get_option('bulk_post_stagger_interval', '0'), '1800'); ?>>30 minutes apart</option>
<option value="3600" <?php selected(get_option('bulk_post_stagger_interval', '0'), '3600'); ?>>1 hour apart</option>
<option value="7200" <?php selected(get_option('bulk_post_stagger_interval', '0'), '7200'); ?>>2 hours apart</option>
<option value="14400" <?php selected(get_option('bulk_post_stagger_interval', '0'), '14400'); ?>>4 hours apart</option>
<option value="21600" <?php selected(get_option('bulk_post_stagger_interval', '0'), '21600'); ?>>6 hours apart</option>
<option value="43200" <?php selected(get_option('bulk_post_stagger_interval', '0'), '43200'); ?>>12 hours apart</option>
<option value="86400" <?php selected(get_option('bulk_post_stagger_interval', '0'), '86400'); ?>>24 hours apart</option>
</select>
<p class="description">When using bulk actions to post multiple posts, schedule them with this time interval between each post. Helps avoid rate limits and makes posting look more natural.</p>
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
<?php $this->display_pending_posts_section(); ?>
<h2>Manage Posts</h2>
<p>To post or re-post content to Threads and/or X, go to the <a href="<?php echo admin_url('edit.php'); ?>">All Posts</a> page. You can use the bulk actions dropdown to post multiple posts at once to either or both platforms.</p>
</div>
<script>
jQuery(document).ready(function($) {
$(document).on('click', '.threads-toggle-visibility', function() {
var $btn = $(this);
var $input = $btn.prev('input');
if ($input.attr('type') === 'password') {
$input.attr('type', 'text');
$btn.text('Hide');
} else {
$input.attr('type', 'password');
$btn.text('Show');
}
});
});
</script>
<?php
}
public function auto_post_to_threads($post_id, $post) {
if ($post->post_type !== 'post' || $post->post_status !== 'publish') {
return;
}
$threads_enabled = get_option('threads_auto_post_enabled');
$x_enabled = get_option('x_auto_post_enabled');
// Check if user made a specific choice during publishing
$publish_choice = get_post_meta($post_id, '_threads_publish_choice', true);
if ($publish_choice === 'none') {
// User chose not to post to social media
return;
}
// Schedule Threads posting in the background if enabled and not already posted
if ($threads_enabled && !get_post_meta($post_id, '_threads_posted', true)) {
$mode = $publish_choice ?: 'auto';
wp_schedule_single_event(time(), 'threads_scheduled_post_to_threads', array($post_id, $mode));
error_log('WordPress to Threads: Scheduled background post to Threads for post ID: ' . $post_id . ' with mode: ' . $mode);
}
// Schedule X posting in the background if enabled and not already posted
if ($x_enabled && !get_post_meta($post_id, '_x_posted', true)) {
wp_schedule_single_event(time(), 'threads_scheduled_post_to_x', array($post_id));
error_log('WordPress to Threads: Scheduled background post to X for post ID: ' . $post_id);
}
}
/**
* X (Twitter) OAuth Flow Methods
*/
public function handle_x_oauth_endpoints() {
if (isset($_GET['x_oauth_action'])) {
switch ($_GET['x_oauth_action']) {
case 'authorize':
$this->initiate_x_oauth();
break;
case 'deauthorize':
$this->handle_x_deauthorize();
break;
}
}
}
public function get_x_authorize_url() {
return add_query_arg('x_oauth_action', 'authorize', admin_url('options-general.php?page=wordpress-to-threads'));
}
public function get_x_deauthorize_url() {
return add_query_arg('x_oauth_action', 'deauthorize', admin_url('options-general.php?page=wordpress-to-threads'));
}
public function get_x_oauth_callback_url() {
return admin_url('admin-post.php?action=x_oauth_callback');
}
private function initiate_x_oauth() {
if (!current_user_can('manage_options')) {
wp_die('Insufficient permissions');
}
$api_key = get_option('x_api_key');
$api_secret = get_option('x_api_secret');
if (empty($api_key) || empty($api_secret)) {
wp_die('Please configure your X API credentials first.');
}
if (!class_exists('Abraham\TwitterOAuth\TwitterOAuth')) {
wp_die('TwitterOAuth library not found');
}
try {
$connection = new \Abraham\TwitterOAuth\TwitterOAuth($api_key, $api_secret);
$callback_url = $this->get_x_oauth_callback_url();
// Request OAuth token
$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => $callback_url));
if (!isset($request_token['oauth_token']) || !isset($request_token['oauth_token_secret'])) {
error_log('X OAuth Error: Failed to get request token - ' . print_r($request_token, true));
wp_die('Failed to initiate X authorization. Please check your API credentials.');
}
// Store the request token temporarily
set_transient('x_oauth_token', $request_token['oauth_token'], 10 * MINUTE_IN_SECONDS);
set_transient('x_oauth_token_secret', $request_token['oauth_token_secret'], 10 * MINUTE_IN_SECONDS);
// Redirect to X authorization page
$authorize_url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
wp_redirect($authorize_url);
exit;
} catch (\Exception $e) {
error_log('X OAuth Error: ' . $e->getMessage());
wp_die('Failed to initiate X authorization: ' . $e->getMessage());
}
}
public function handle_x_oauth_callback() {
if (!isset($_GET['oauth_token']) || !isset($_GET['oauth_verifier'])) {
wp_die('Invalid OAuth callback - missing parameters');
}
$oauth_token = sanitize_text_field($_GET['oauth_token']);
$oauth_verifier = sanitize_text_field($_GET['oauth_verifier']);
// Retrieve stored request token
$stored_oauth_token = get_transient('x_oauth_token');
$stored_oauth_token_secret = get_transient('x_oauth_token_secret');
if ($oauth_token !== $stored_oauth_token || empty($stored_oauth_token_secret)) {
error_log('X OAuth Error: Token mismatch. Received: ' . $oauth_token . ', Stored: ' . $stored_oauth_token);
wp_die('OAuth token mismatch');
}
$api_key = get_option('x_api_key');
$api_secret = get_option('x_api_secret');
if (!class_exists('Abraham\TwitterOAuth\TwitterOAuth')) {
wp_die('TwitterOAuth library not found');
}
try {
$connection = new \Abraham\TwitterOAuth\TwitterOAuth(
$api_key,
$api_secret,
$stored_oauth_token,
$stored_oauth_token_secret
);
// Exchange for access token
$access_token = $connection->oauth('oauth/access_token', array('oauth_verifier' => $oauth_verifier));
if (!isset($access_token['oauth_token']) || !isset($access_token['oauth_token_secret'])) {
error_log('X OAuth Error: Failed to get access token - ' . print_r($access_token, true));
wp_die('Failed to complete X authorization');
}
// Save access token and secret
update_option('x_access_token', $access_token['oauth_token']);
update_option('x_access_token_secret', $access_token['oauth_token_secret']);
// Save user info if available
if (isset($access_token['screen_name'])) {
update_option('x_username', $access_token['screen_name']);
}
if (isset($access_token['user_id'])) {
update_option('x_user_id', $access_token['user_id']);
}
// Clean up transients
delete_transient('x_oauth_token');
delete_transient('x_oauth_token_secret');
error_log('X OAuth: Successfully authorized as @' . $access_token['screen_name']);
$wizard_return = get_transient('x_wizard_oauth_return');
delete_transient('x_wizard_oauth_return');
if ($wizard_return) {
$step = intval($wizard_return) > 1 ? intval($wizard_return) : 3;
wp_redirect(admin_url('options-general.php?page=wordpress-to-threads-setup&step=' . $step . '&x_authorized=1'));
} else {
wp_redirect(admin_url('options-general.php?page=wordpress-to-threads&x_authorized=1'));
}
exit;
} catch (\Exception $e) {
error_log('X OAuth Error: ' . $e->getMessage());
wp_die('Failed to complete X authorization: ' . $e->getMessage());
}
}
private function handle_x_deauthorize() {
if (!current_user_can('manage_options')) {
wp_die('Insufficient permissions');
}
delete_option('x_access_token');
delete_option('x_access_token_secret');
delete_option('x_username');
delete_option('x_user_id');
wp_redirect(admin_url('options-general.php?page=wordpress-to-threads&x_deauthorized=1'));
exit;
}
public function post_to_threads($post, $force_mode = null) {
$user_id = get_option('threads_user_id');
if (empty($user_id)) {
error_log('WordPress to Threads: Missing user ID. Please authorize the plugin.');
return false;
}
// Ensure we have a valid access token (will refresh if needed)
$access_token = $this->ensure_valid_token();
if (empty($access_token)) {
error_log('WordPress to Threads: Could not obtain valid access token. Please re-authorize the plugin.');
return false;
}
// Check if user forced a specific posting mode
if ($force_mode === 'chain') {
error_log('WordPress to Threads: User forced thread chain mode');
return $this->create_thread_chain($post);
} elseif ($force_mode === 'single') {
error_log('WordPress to Threads: User forced single post mode');
// Skip the length check and go straight to single post
} else {
// Check if we should use thread chains for long content (default behavior)
$enable_thread_chains = get_option('threads_enable_thread_chains', '1') === '1';
$title = wp_strip_all_tags($post->post_title);
$content = wp_strip_all_tags($post->post_content);
$full_text = $title . "\n\n" . $content;
if ($enable_thread_chains && strlen($full_text) > $this->threads_character_limit) {
error_log('WordPress to Threads: Content exceeds character limit, using thread chain');
return $this->create_thread_chain($post);
}
}
// Use original single-post method for shorter content
$post_content = $this->prepare_post_content($post);
if (!$post_content) {
error_log('WordPress to Threads: Failed to prepare post content');
return false;
}
// Check for media in the post (if enabled)
$media_items = array();
if (get_option('threads_include_media', '1') === '1') {
$media_items = $this->extract_post_images_and_videos($post);
}
$final_container_id = $this->create_media_or_text_container($media_items, $post_content, $user_id, $access_token);
if (!$final_container_id) {
return false;
}
$has_video = $this->media_contains_video($media_items);
$publish_response = $this->publish_threads_container($user_id, $final_container_id, $access_token, $has_video);
if (!$publish_response || !isset($publish_response['id'])) {
error_log('WordPress to Threads: Failed to publish container. Response: ' . print_r($publish_response, true));
return false;
}
error_log('WordPress to Threads: Post published successfully. ID: ' . $publish_response['id']);
update_post_meta($post->ID, '_threads_posted', '1');
update_post_meta($post->ID, '_threads_post_id', $publish_response['id']);
// Add attribution reply
if (get_option('threads_attribution_reply_enabled', '1') === '1') {
$this->post_attribution_reply($post, $publish_response['id'], $user_id, $access_token);
}
return true;
}
private function prepare_post_content($post) {
$title = wp_strip_all_tags($post->post_title);
$content = wp_strip_all_tags($post->post_content);
$full_text = $title . "\n\n" . $content;
if (strlen($full_text) <= $this->threads_character_limit) {
return $full_text;
}
$attribution_enabled = get_option('threads_attribution_reply_enabled', '1') === '1';
if ($attribution_enabled) {
// Attribution reply will provide the link — just truncate with "..."
$available_chars = $this->threads_character_limit - 3;
if (strlen($title) + 2 < $available_chars) {
$remaining_chars = $available_chars - strlen($title) - 2;
return $title . "\n\n" . substr($content, 0, $remaining_chars) . '...';
} else {
return substr($title, 0, $available_chars) . '...';
}
}
$url_to_use = $this->get_post_url($post->ID);
$available_chars = $this->threads_character_limit - strlen($url_to_use) - 2;
if (strlen($title) + 2 < $available_chars) {
$remaining_chars = $available_chars - strlen($title) - 2;
$truncated_content = substr($content, 0, $remaining_chars - 10) . '... More: ';
return $title . "\n\n" . $truncated_content . $url_to_use;
} else {
$truncated_title = substr($title, 0, $available_chars - 10) . '... More: ';
return $truncated_title . $url_to_use;
}
}
private function split_content_for_thread_chain($post) {
$title = wp_strip_all_tags($post->post_title);
$content = wp_strip_all_tags($post->post_content);
$split_preference = get_option('threads_split_preference', 'sentences');
$max_chain_length = (int) get_option('threads_max_chain_length', 5);
$url_to_use = $this->get_post_url($post->ID);
$attribution_enabled = get_option('threads_attribution_reply_enabled', '1') === '1';
// Full text with title and content
$full_text = $title . "\n\n" . $content;
// Calculate available characters for content (reserve space for URL at the end and thread indicators)
// When attribution reply is enabled, no URL needed on the last post so no space reservation required.
$available_chars_last_post = $attribution_enabled
? $this->threads_character_limit
: $this->threads_character_limit - strlen('... More: ' . $url_to_use);
$available_chars_regular = $this->threads_character_limit;
// Reserve space for thread indicator on first post (only used when multiple posts)
$thread_indicator = "\n🧵";
$thread_indicator_len = strlen($thread_indicator);
$thread_parts = array();
$remaining_text = $full_text;
$part_count = 0;
while (!empty($remaining_text) && $part_count < $max_chain_length) {
$part_count++;
$is_first_part = ($part_count == 1);
$is_last_part = ($part_count == $max_chain_length);
// Reserve space on the first post for the thread indicator
$char_limit = $is_last_part ? $available_chars_last_post : $available_chars_regular;
if ($is_first_part) {
$char_limit -= $thread_indicator_len;
}
if (strlen($remaining_text) <= $char_limit) {
// Remaining text fits in this part
$part_text = $remaining_text;
if (!$attribution_enabled && ($is_last_part || $part_count == 1)) {
$part_text .= "\n\n" . $url_to_use;
}
$thread_parts[] = $part_text;
break;
}
// Need to split the content
$split_point = $this->find_split_point($remaining_text, $char_limit, $split_preference);
if ($split_point === false) {
// No good split point found, force split at character limit
$split_point = $char_limit - 3; // Leave room for "..."
$part_text = substr($remaining_text, 0, $split_point) . '...';
} else {
$part_text = substr($remaining_text, 0, $split_point);
}
// Add URL to the last part only (when attribution reply is disabled)
if ($is_last_part && !$attribution_enabled) {
// We're at max chain length and truncating content - use "... More: " format
$part_text = rtrim($part_text);
if (substr($part_text, -3) !== '...') {
$part_text .= '...';
}
$part_text .= ' More: ' . $url_to_use;
}
$thread_parts[] = trim($part_text);
$remaining_text = trim(substr($remaining_text, $split_point));
}
// If we still have remaining text and hit the max chain length, append URL to last part (when attribution reply is disabled)
if (!empty($remaining_text) && !$attribution_enabled && strpos(end($thread_parts), $url_to_use) === false) {
$last_part = array_pop($thread_parts);
$last_part = rtrim($last_part);
if (substr($last_part, -3) !== '...') {
$last_part .= '...';
}
$last_part .= ' More: ' . $url_to_use;
$thread_parts[] = $last_part;
}
// Add thread indicator to the first post when there are multiple posts
if (count($thread_parts) > 1) {
$thread_parts[0] = rtrim($thread_parts[0]) . $thread_indicator;
}
return $thread_parts;
}
private function find_split_point($text, $max_length, $split_preference) {
if (strlen($text) <= $max_length) {
return strlen($text);
}
// Get the portion we're considering for splitting
$search_text = substr($text, 0, $max_length);
switch ($split_preference) {
case 'sentences':
// Look for sentence endings (. ! ?) followed by space or end of string
if (preg_match('/.*[.!?](?=\s|$)/s', $search_text, $matches)) {
return strlen($matches[0]);
}
// Fall through to paragraph splitting if no sentence boundary found
case 'paragraphs':
// Look for double newlines (paragraph breaks)
$last_paragraph = strrpos($search_text, "\n\n");
if ($last_paragraph !== false && $last_paragraph > $max_length * 0.5) {
return $last_paragraph + 2; // Include the paragraph break
}
// Fall through to word splitting if no paragraph boundary found
case 'words':
default:
// Look for last complete word
$last_space = strrpos($search_text, ' ');
if ($last_space !== false && $last_space > $max_length * 0.7) {
return $last_space + 1; // Include the space
}
break;
}
return false; // No good split point found
}
private function post_attribution_reply($post, $reply_to_id, $user_id, $access_token) {
$post_url = get_permalink($post->ID);
$attribution_text = "Originally published on my blog: " . $post_url . "\nPublished by WordpressToThreads https://github.com/Xatter/WordpressToThreads";
$reply_data = array(
'media_type' => 'TEXT',
'text' => $attribution_text,
'reply_to_id' => $reply_to_id,
);
$container_response = $this->create_threads_container($user_id, $reply_data, $access_token);
if (!$container_response || !isset($container_response['id'])) {
error_log('WordPress to Threads: Failed to create attribution reply container.');
return;
}
$publish_response = $this->publish_threads_container($user_id, $container_response['id'], $access_token);
if (!$publish_response || !isset($publish_response['id'])) {
error_log('WordPress to Threads: Failed to publish attribution reply.');
return;
}
error_log('WordPress to Threads: Attribution reply published. ID: ' . $publish_response['id']);
}
private function create_thread_chain($post) {
$user_id = get_option('threads_user_id');
if (empty($user_id)) {
error_log('WordPress to Threads: Missing user ID for thread chain. Please authorize the plugin.');
return false;
}
// Ensure we have a valid access token
$access_token = $this->ensure_valid_token();
if (empty($access_token)) {
error_log('WordPress to Threads: Could not obtain valid access token for thread chain. Please re-authorize the plugin.');
return false;
}
// Split content into thread parts
$thread_parts = $this->split_content_for_thread_chain($post);
if (empty($thread_parts)) {
error_log('WordPress to Threads: No thread parts generated');
return false;
}
error_log('WordPress to Threads: Creating thread chain with ' . count($thread_parts) . ' parts');
$thread_post_ids = array();
$main_post_id = null;
$previous_post_id = null;
// Process each part of the thread
foreach ($thread_parts as $index => $part_content) {
$is_first_post = ($index === 0);
// Check for media in the first post only (if enabled)
$media_items = array();
if ($is_first_post && get_option('threads_include_media', '1') === '1') {
$media_items = $this->extract_post_images_and_videos($post);
}
// Prepare the thread post data - add reply_to_id for non-first posts
$thread_post_data = array(
'media_type' => 'TEXT',
'text' => $part_content
);
// For reply posts, add reply_to_id parameter (reply to previous post in chain)
if (!$is_first_post && $previous_post_id) {
$thread_post_data['reply_to_id'] = $previous_post_id;
}
// Create container with media (first post only) or text-only
$container_media = ($is_first_post) ? $media_items : array();
$final_container_id = $this->create_media_or_text_container($container_media, $part_content, $user_id, $access_token, $thread_post_data);
if (!$final_container_id) {
error_log('WordPress to Threads: Failed to create thread part ' . ($index + 1) . ' container');
return false;
}
error_log('WordPress to Threads: Thread part ' . ($index + 1) . ' container created. ID: ' . $final_container_id);
$has_video = ($is_first_post) ? $this->media_contains_video($media_items) : false;
$publish_response = $this->publish_threads_container($user_id, $final_container_id, $access_token, $has_video);
if (!$publish_response || !isset($publish_response['id'])) {
error_log('WordPress to Threads: Failed to publish thread part ' . ($index + 1) . '. Response: ' . print_r($publish_response, true));
return false;
}
$published_post_id = $publish_response['id'];
$thread_post_ids[] = $published_post_id;
// Store the main post ID and update previous post ID for sequential replies
if ($is_first_post) {
$main_post_id = $published_post_id;
}
$previous_post_id = $published_post_id;
error_log('WordPress to Threads: Thread part ' . ($index + 1) . ' published successfully. ID: ' . $published_post_id . ($is_first_post ? ' (main post)' : ' (reply to previous post)'));
// Add a small delay between posts to avoid rate limiting
if ($index < count($thread_parts) - 1) {
sleep(3); // Slightly longer delay to ensure main post is fully processed before creating replies
}
}
// Add attribution reply to the last post in the chain
if (get_option('threads_attribution_reply_enabled', '1') === '1') {
sleep(3);
$this->post_attribution_reply($post, $previous_post_id, $user_id, $access_token);
}
// Store thread chain information in post meta
update_post_meta($post->ID, '_threads_posted', '1');
update_post_meta($post->ID, '_threads_post_id', $thread_post_ids[0]); // Main post ID
update_post_meta($post->ID, '_threads_chain_ids', $thread_post_ids); // All post IDs
update_post_meta($post->ID, '_threads_chain_count', count($thread_post_ids));
error_log('WordPress to Threads: Sequential thread chain created successfully with ' . count($thread_post_ids) . ' posts');
return true;
}
/**
* Create a media container (carousel, single media, or text-only fallback)
*
* @param array $media_items Media items to include (empty for text-only)
* @param string $text Post text content
* @param string $user_id Threads user ID
* @param string $access_token Threads access token
* @param array|null $fallback_data Custom data for text-only fallback (e.g. with reply_to_id)
* @return string|false Container ID or false on failure
*/
/**
* Get the best URL for a post (shortened if Bitly is configured)
*/
private function get_post_url($post_id) {
$post_url = get_permalink($post_id);
$bitly_token = get_option('bitly_access_token');
if (!empty($bitly_token)) {
$short_url = $this->shorten_url($post_url);
if ($short_url) {
return $short_url;