-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexport_wp_posts.sh
More file actions
executable file
·1602 lines (1403 loc) · 59.6 KB
/
export_wp_posts.sh
File metadata and controls
executable file
·1602 lines (1403 loc) · 59.6 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
#!/bin/bash
################################################################################
# Script Name: export_wp_posts.sh
#
# Description:
# Unified WordPress export script that can run either locally or via SSH.
# Exports WordPress posts and custom permalink information using WP-CLI,
# then merges the data into a final CSV with columns in the order:
# ID, post_title, post_name, custom_permalink, post_date, post_status, post_type.
#
# Additionally exports WordPress users with their details and post counts
# across all public post types (excluding attachments).
#
# Generates a final Excel (.xlsx) file with:
# - Row 1: editable base domain
# - Row 2: headers
# - Column A: formula-generated URLs
# - Column I: WP Admin edit links
#
# Author: Eric Rasch
# GitHub: https://github.com/ericrasch/script-export-wp-posts
# Date Created: 2025-08-11
# Last Modified: 2025-08-12
# Version: 5.0
#
# Usage:
# ./export_wp_posts.sh
#
# Output Files (in timestamped directory with domain name):
# - export_all_posts.csv: Exported post details
# - export_custom_permalinks.csv: Exported custom_permalink data
# - export_wp_posts_<timestamp>.csv: Final merged posts file
# - export_wp_posts_<timestamp>.xlsx: Final Excel file with formulas
# - export_users.csv: Raw export of user details
# - export_users_with_post_counts.csv: Users with post counts
# - export_debug_log.txt: Debug log (if DEBUG mode enabled)
#
# Configuration:
# Config file is stored at .config/wp-export-config.json in the script directory
# Stores recent domains, SSH connections, and export statistics
################################################################################
set -euo pipefail
# Parse command-line arguments
REMOTE_MODE=0
VERBOSE=0
DEBUG=0
for arg in "$@"; do
case "$arg" in
--remote|-r) REMOTE_MODE=1 ;;
--verbose|-v) VERBOSE=1 ;;
--debug) DEBUG=1; VERBOSE=1 ;;
esac
done
# Pre-flight check: verify Python + openpyxl for Excel generation
EXCEL_AVAILABLE=0
for cmd in python3 /usr/bin/python3 /usr/local/bin/python3 /opt/homebrew/bin/python3; do
if command -v $cmd &> /dev/null; then
export PYTHONPATH="$HOME/.local/lib/python3.*/site-packages:${PYTHONPATH:-}"
if $cmd -c "import openpyxl" 2>/dev/null; then
EXCEL_AVAILABLE=1
break
fi
fi
done
if [ "$EXCEL_AVAILABLE" -eq 0 ]; then
# Check if Python 3 exists at all (needed for both install and Excel)
PREFLIGHT_PYTHON=""
for cmd in python3 /usr/bin/python3 /usr/local/bin/python3 /opt/homebrew/bin/python3; do
if command -v $cmd &> /dev/null; then
PREFLIGHT_PYTHON=$cmd
break
fi
done
echo -e "${YELLOW}⚠️ Excel generation is not available (Python 3 + openpyxl required).${NC}"
echo ""
if [ -n "$PREFLIGHT_PYTHON" ]; then
echo " i) Install openpyxl now and continue"
fi
echo " c) Continue anyway (CSV export only)"
echo " q) Quit"
echo ""
read -rp "Choose an option: " EXCEL_CHOICE
EXCEL_CHOICE=$(echo "$EXCEL_CHOICE" | tr '[:upper:]' '[:lower:]')
case "$EXCEL_CHOICE" in
i)
if [ -z "$PREFLIGHT_PYTHON" ]; then
echo -e "${RED}Python 3 is not installed. Install it first (e.g., brew install python@3).${NC}"
exit 1
fi
echo ""
echo "Installing openpyxl..."
# Detect pip version to determine if --break-system-packages is needed
PIP_VERSION=$($PREFLIGHT_PYTHON -m pip --version 2>/dev/null | awk '{print $2}')
BREAK_FLAG=""
if [[ "$PIP_VERSION" =~ ^([0-9]+)\. ]] && (( ${BASH_REMATCH[1]} >= 23 )); then
BREAK_FLAG="--break-system-packages"
fi
if $PREFLIGHT_PYTHON -m pip install --user $BREAK_FLAG openpyxl; then
echo -e "${GREEN}✅ openpyxl installed successfully!${NC}"
EXCEL_AVAILABLE=1
else
echo -e "${RED}❌ Installation failed.${NC}"
read -rp "Continue without Excel? (y/N): " FALLBACK_CHOICE
if [[ ! "$FALLBACK_CHOICE" =~ ^[Yy]$ ]]; then
exit 1
fi
fi
;;
c)
echo "Continuing without Excel export..."
;;
*)
echo "Exiting."
exit 0
;;
esac
echo ""
fi
# Expected final columns for merged posts (computed dynamically after meta field prompt):
# Base: ID, post_title, post_name, custom_permalink, post_date, post_status, post_type = 7
# Plus any custom meta fields the user adds
EXPECTED_COLUMNS=7
# Flag: set to 1 when permalink structure requires full path export
EXPORT_PERMALINK_PATH=0
PERMALINK_PATH_FILE=""
HOME_URL=""
# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'
# SSH options (consistent across all SSH calls)
SSH_OPTS="-T -o ServerAliveInterval=5 -o ServerAliveCountMax=3 -o ConnectTimeout=30"
# Route SSH stderr to terminal in verbose mode, suppress otherwise
if [ "$VERBOSE" -eq 1 ]; then
SSH_STDERR="/dev/stderr"
else
SSH_STDERR="/dev/null"
fi
# Sudo prefix for remote commands (set during RemoteCommand detection)
SUDO_PREFIX=""
# Build a remote command string, wrapping with sudo if needed
# Usage: build_remote_cmd "cd /path && wp post-type list"
build_remote_cmd() {
local cmd="$1"
if [ -n "$SUDO_PREFIX" ]; then
# Wrap in sudo -iu <user> bash -c '...'
# Escape single quotes in the command for bash -c wrapping
local escaped_cmd="${cmd//\'/\'\\\'\'}"
echo "$SUDO_PREFIX bash -c '$escaped_cmd'"
else
echo "$cmd"
fi
}
# Configuration directory and file
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
CONFIG_DIR="$SCRIPT_DIR/.config"
CONFIG_FILE="$CONFIG_DIR/wp-export-config.json"
MAX_RECENT_DOMAINS=10
MAX_SSH_FAVORITES=10
#########################################
# Configuration Functions
#########################################
# Initialize configuration directory and file
init_config() {
if [ ! -d "$CONFIG_DIR" ]; then
mkdir -p "$CONFIG_DIR"
fi
if [ ! -f "$CONFIG_FILE" ]; then
cat > "$CONFIG_FILE" << 'EOF'
{
"recent_domains": [],
"ssh_favorites": [],
"export_stats": {
"total_exports": 0,
"last_export": null
}
}
EOF
fi
}
# Load configuration
load_config() {
init_config
if [ -f "$CONFIG_FILE" ]; then
cat "$CONFIG_FILE"
else
echo '{"recent_domains":[],"ssh_favorites":[],"export_stats":{"total_exports":0,"last_export":null}}'
fi
}
# Save configuration (with validation to prevent writing empty/corrupt data)
save_config() {
local config_data="$1"
# Validate that config_data is non-empty and valid JSON before writing
if [ -z "$config_data" ]; then
echo "Warning: Refusing to save empty config data" >&2
return 1
fi
if ! echo "$config_data" | python3 -c "import json,sys; json.load(sys.stdin)" 2>/dev/null; then
echo "Warning: Refusing to save invalid JSON config data" >&2
return 1
fi
echo "$config_data" > "$CONFIG_FILE"
}
# Add domain to recent history (with deduplication and limit)
add_domain_to_history() {
local domain="$1"
local config=$(load_config)
# Add new domain to the beginning, remove duplicates, and limit to MAX_RECENT_DOMAINS
local updated_config
updated_config=$(echo "$config" | python3 -c "
import json, sys
from datetime import datetime, timezone
config = json.load(sys.stdin)
domain = '$domain'
domains = config.get('recent_domains', [])
domain_stats = config.get('domain_stats', {})
# Remove existing occurrence if present
if domain in domains:
domains.remove(domain)
# Add to beginning
domains.insert(0, domain)
# Limit to max
config['recent_domains'] = domains[:$MAX_RECENT_DOMAINS]
# Update domain stats
if 'domain_stats' not in config:
config['domain_stats'] = {}
if domain not in config['domain_stats']:
config['domain_stats'][domain] = {}
config['domain_stats'][domain]['last_export'] = datetime.now(timezone.utc).isoformat()
config['domain_stats'][domain]['export_count'] = config['domain_stats'][domain].get('export_count', 0) + 1
print(json.dumps(config, indent=2))
") || true
save_config "$updated_config" || echo "Warning: Failed to save domain history" >&2
}
# Add SSH connection to favorites
add_ssh_to_favorites() {
local ssh_connection="$1"
local wp_path="$2"
local config=$(load_config)
local updated_config
updated_config=$(echo "$config" | python3 -c "
import json, sys
config = json.load(sys.stdin)
connection = '$ssh_connection'
path = '$wp_path'
favorites = config.get('ssh_favorites', [])
# Create entry
entry = {'connection': connection, 'path': path}
# Remove existing if present
favorites = [f for f in favorites if f.get('connection') != connection]
# Add to beginning
favorites.insert(0, entry)
# Limit to max
config['ssh_favorites'] = favorites[:$MAX_SSH_FAVORITES]
print(json.dumps(config, indent=2))
") || true
save_config "$updated_config" || echo "Warning: Failed to save SSH favorites" >&2
}
# Get recent domains as array with timestamps
get_recent_domains() {
local config=$(load_config)
echo "$config" | python3 -c "
import json, sys
from datetime import datetime, timezone
config = json.load(sys.stdin)
domains = config.get('recent_domains', [])
domain_stats = config.get('domain_stats', {})
for domain in domains:
stats = domain_stats.get(domain, {})
last_export = stats.get('last_export', '')
if last_export:
try:
# Parse the timestamp and calculate days ago
export_date = datetime.fromisoformat(last_export.replace('Z', '+00:00'))
now = datetime.now(timezone.utc)
days_ago = (now - export_date).days
if days_ago == 0:
time_str = 'today'
elif days_ago == 1:
time_str = 'yesterday'
else:
time_str = f'{days_ago} days ago'
print(f'{domain}|{time_str}')
except:
print(f'{domain}|never')
else:
print(f'{domain}|never')
"
}
# Get SSH favorites
get_ssh_favorites() {
local config=$(load_config)
echo "$config" | python3 -c "
import json, sys
config = json.load(sys.stdin)
favorites = config.get('ssh_favorites', [])
for i, fav in enumerate(favorites):
print(f'{i+1}|{fav.get(\"connection\", \"\")}|{fav.get(\"path\", \"\")}')
"
}
# Get saved meta keys for a domain
get_domain_meta_keys() {
local domain="$1"
local config=$(load_config)
echo "$config" | python3 -c "
import json, sys
config = json.load(sys.stdin)
domain = '$domain'
stats = config.get('domain_stats', {}).get(domain, {})
meta_keys = stats.get('meta_keys', [])
for key in meta_keys:
print(key)
" 2>/dev/null || true
}
# Save meta keys for a domain
save_domain_meta_keys() {
local domain="$1"
shift
local meta_keys=("$@")
local config=$(load_config)
# Build a JSON array of meta keys
local meta_json="["
local first=1
for key in "${meta_keys[@]}"; do
if [ "$first" -eq 1 ]; then
meta_json="$meta_json\"$key\""
first=0
else
meta_json="$meta_json,\"$key\""
fi
done
meta_json="$meta_json]"
local updated_config
updated_config=$(echo "$config" | python3 -c "
import json, sys
config = json.load(sys.stdin)
domain = '$domain'
meta_keys = json.loads('$meta_json')
if 'domain_stats' not in config:
config['domain_stats'] = {}
if domain not in config['domain_stats']:
config['domain_stats'][domain] = {}
config['domain_stats'][domain]['meta_keys'] = meta_keys
print(json.dumps(config, indent=2))
") || true
save_config "$updated_config" || echo "Warning: Failed to save meta keys" >&2
}
# Update export statistics
update_export_stats() {
local domain="$1"
local config=$(load_config)
local timestamp=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
local updated_config
updated_config=$(echo "$config" | python3 -c "
import json, sys
config = json.load(sys.stdin)
stats = config.get('export_stats', {})
stats['total_exports'] = stats.get('total_exports', 0) + 1
stats['last_export'] = '$timestamp'
stats['last_domain'] = '$domain'
config['export_stats'] = stats
print(json.dumps(config, indent=2))
") || true
save_config "$updated_config" || echo "Warning: Failed to save export stats" >&2
}
#########################################
# Mode Selection
#########################################
echo -e "${GREEN}=== WordPress Export Script v5.0 ===${NC}"
if [ "$VERBOSE" -eq 1 ]; then
echo -e "${YELLOW}Verbose mode enabled — SSH debug output will be shown${NC}"
fi
# Skip mode selection if --remote was passed via CLI
if [ "$REMOTE_MODE" -eq 0 ]; then
echo ""
echo "Select export mode:"
echo " 1) Local WordPress"
echo " 2) Remote WordPress (SSH)"
echo ""
read -rp "Enter choice (1 or 2): " MODE_CHOICE
if [[ "$MODE_CHOICE" == "2" ]]; then
REMOTE_MODE=1
fi
fi
#########################################
# Local vs Remote Setup
#########################################
if [ "$REMOTE_MODE" -eq 0 ]; then
echo -e "\n${GREEN}Local Mode Selected${NC}"
# Check for WP-CLI locally
if ! command -v wp &> /dev/null; then
echo "❌ Error: WP-CLI (wp) is not installed or not in PATH."
echo "Please install WP-CLI before running this script."
echo ""
echo "Install instructions: https://wp-cli.org/#installing"
exit 1
fi
# Set local environment
export LC_ALL=C
WP_PATH="."
else
echo -e "\n${GREEN}Remote Mode Selected${NC}"
echo "This script exports all post types and custom permalinks via SSH."
# Function to parse SSH config
parse_ssh_config() {
local config_file="${1:-$HOME/.ssh/config}"
local hosts=()
if [ -f "$config_file" ]; then
while IFS= read -r line; do
if [[ "$line" =~ ^Host[[:space:]]+(.+)$ ]]; then
local host="${BASH_REMATCH[1]}"
if [[ ! "$host" =~ [*?] ]] && [[ ! "$host" =~ github ]]; then
hosts+=("$host")
fi
fi
done < "$config_file"
fi
printf '%s\n' "${hosts[@]}"
}
# Get SSH favorites from config
SSH_FAVORITES=()
while IFS='|' read -r idx connection path; do
if [ -n "$connection" ]; then
SSH_FAVORITES+=("$idx|$connection|$path")
fi
done < <(get_ssh_favorites)
# Check for SSH config hosts
SSH_HOSTS=($(parse_ssh_config))
echo -e "\n${YELLOW}SSH Connection Options:${NC}"
# Show favorites if any
if [ ${#SSH_FAVORITES[@]} -gt 0 ]; then
echo -e "\n${GREEN}Recent SSH connections:${NC}"
for fav in "${SSH_FAVORITES[@]}"; do
IFS='|' read -r idx connection path <<< "$fav"
echo " F$idx. $connection (path: $path)"
done
fi
# Show SSH config hosts
if [ ${#SSH_HOSTS[@]} -gt 0 ]; then
echo -e "\n${YELLOW}SSH config hosts:${NC}"
for i in "${!SSH_HOSTS[@]}"; do
echo " $((i+1)). ${SSH_HOSTS[$i]}"
done
fi
echo " 0. Enter custom connection"
# Get selection
if [ ${#SSH_FAVORITES[@]} -gt 0 ]; then
read -rp $'\nSelect an option (F1-F'${#SSH_FAVORITES[@]}', 1-'${#SSH_HOSTS[@]}', or 0): ' HOST_CHOICE
else
read -rp $'\nSelect a host (1-'${#SSH_HOSTS[@]}') or 0 for custom: ' HOST_CHOICE
fi
# Process selection
HOST_CHOICE_UPPER=$(echo "$HOST_CHOICE" | tr '[:lower:]' '[:upper:]')
if [[ "$HOST_CHOICE_UPPER" =~ ^F([0-9]+)$ ]]; then
# Favorite selected — pre-fill connection and path, allow override
FAV_NUM="${BASH_REMATCH[1]}"
FAV_CONNECTION=""
FAV_PATH=""
for fav in "${SSH_FAVORITES[@]}"; do
IFS='|' read -r idx connection path <<< "$fav"
if [[ "$idx" == "$FAV_NUM" ]]; then
FAV_CONNECTION="$connection"
FAV_PATH="$path"
break
fi
done
if [ -n "$FAV_CONNECTION" ]; then
echo -e "${GREEN}Favorite: $FAV_CONNECTION (path: $FAV_PATH)${NC}"
read -rp "SSH connection [$FAV_CONNECTION]: " SSH_CONNECTION
SSH_CONNECTION=${SSH_CONNECTION:-$FAV_CONNECTION}
read -rp "WordPress path [$FAV_PATH]: " WP_PATH
WP_PATH=${WP_PATH:-$FAV_PATH}
fi
elif [[ "$HOST_CHOICE" =~ ^[1-9][0-9]*$ ]] && [ "$HOST_CHOICE" -le "${#SSH_HOSTS[@]}" ]; then
# SSH config host selected
SSH_CONNECTION="${SSH_HOSTS[$((HOST_CHOICE-1))]}"
echo -e "${GREEN}Using: $SSH_CONNECTION${NC}"
# Check if this host has a saved path in favorites
SAVED_PATH=""
for fav in ${SSH_FAVORITES[@]+"${SSH_FAVORITES[@]}"}; do
IFS='|' read -r idx fav_conn fav_path <<< "$fav"
if [[ "$fav_conn" == "$SSH_CONNECTION" ]]; then
SAVED_PATH="$fav_path"
break
fi
done
if [ -n "$SAVED_PATH" ]; then
echo -e "${YELLOW}Previous path found: $SAVED_PATH${NC}"
read -rp "Enter WordPress path (previous: $SAVED_PATH): " WP_PATH
WP_PATH=${WP_PATH:-$SAVED_PATH}
else
# Auto-detect common paths based on hostname patterns
DETECTED_HOST=""
if [[ "$SSH_CONNECTION" =~ press ]] || [[ "$SSH_CONNECTION" =~ pressable ]]; then
SUGGESTED_PATH="/htdocs"
DETECTED_HOST="Pressable"
elif [[ "$SSH_CONNECTION" =~ wpe ]] || [[ "$SSH_CONNECTION" =~ wpengine ]]; then
SITE_NAME="${SSH_CONNECTION#wpe-}"
SITE_NAME="${SITE_NAME%%.*}"
SUGGESTED_PATH="/home/wpe-user/sites/$SITE_NAME"
DETECTED_HOST="WP Engine"
elif [[ "$SSH_CONNECTION" =~ kinsta ]]; then
SUGGESTED_PATH="/www/[sitename]_[id]/public"
DETECTED_HOST="Kinsta"
elif [[ "$SSH_CONNECTION" =~ siteground ]]; then
SUGGESTED_PATH="~/public_html"
DETECTED_HOST="SiteGround"
elif [[ "$SSH_CONNECTION" =~ ec2 ]] || [[ "$SSH_CONNECTION" =~ amazonaws ]] || [[ "$SSH_CONNECTION" =~ aws ]]; then
SUGGESTED_PATH="/var/www/html"
DETECTED_HOST="AWS/EC2"
elif [[ "$SSH_CONNECTION" =~ bitnami ]]; then
SUGGESTED_PATH="/opt/bitnami/wordpress"
DETECTED_HOST="Bitnami"
elif [[ "$SSH_CONNECTION" =~ lightsail ]]; then
SUGGESTED_PATH="/opt/bitnami/wordpress"
DETECTED_HOST="AWS Lightsail"
elif [[ "$SSH_CONNECTION" =~ cloudways ]]; then
SUGGESTED_PATH="~/public_html"
DETECTED_HOST="Cloudways"
elif [[ "$SSH_CONNECTION" =~ flywheel ]] || [[ "$SSH_CONNECTION" =~ getflywheel ]]; then
SUGGESTED_PATH="~/public_html"
DETECTED_HOST="Flywheel"
else
SUGGESTED_PATH="~/public_html"
fi
# Get WordPress path
if [ -n "$SUGGESTED_PATH" ]; then
if [ -n "$DETECTED_HOST" ]; then
echo -e "${YELLOW}Detected: $DETECTED_HOST host${NC}"
fi
read -rp "Enter WordPress path (suggested: $SUGGESTED_PATH): " WP_PATH
WP_PATH=${WP_PATH:-$SUGGESTED_PATH}
else
read -rp "Enter WordPress path (e.g., ~/htdocs): " WP_PATH
fi
fi # end of saved path else block
else
# Custom connection
read -rp "Enter SSH user@host: " SSH_CONNECTION
read -rp "Enter WordPress path (e.g., ~/htdocs): " WP_PATH
fi
# Detect SSH config overrides (RemoteCommand, RequestTTY)
# These prevent passing commands via CLI and must be overridden for scripted use
SUDO_PREFIX=""
SSH_CONFIG_REMOTE_CMD=$(ssh -G "$SSH_CONNECTION" 2>/dev/null | grep -i "^remotecommand " | sed 's/^remotecommand //i' || true)
if [ -n "$SSH_CONFIG_REMOTE_CMD" ] && [[ "$SSH_CONFIG_REMOTE_CMD" != "none" ]]; then
echo -e "\n${YELLOW}Detected RemoteCommand in SSH config for $SSH_CONNECTION${NC}"
[ "$VERBOSE" -eq 1 ] && echo " [DEBUG] RemoteCommand: $SSH_CONFIG_REMOTE_CMD"
# Override RemoteCommand and RequestTTY so we can pass commands
SSH_OPTS="$SSH_OPTS -o RemoteCommand=none -o RequestTTY=no"
echo " Overriding RemoteCommand for scripted access"
# Extract sudo user if the RemoteCommand uses sudo -iu <user>
if [[ "$SSH_CONFIG_REMOTE_CMD" =~ sudo\ -iu\ ([a-zA-Z0-9_-]+) ]]; then
SUDO_USER="${BASH_REMATCH[1]}"
SUDO_PREFIX="sudo -iu $SUDO_USER"
echo -e " Detected sudo user: ${GREEN}$SUDO_USER${NC} — will wrap WP-CLI commands with '$SUDO_PREFIX'"
fi
fi
# Validate SSH connection before proceeding
echo -e "\n${YELLOW}Validating SSH connection...${NC}"
# Test 1: Can we connect at all?
echo -n " Testing SSH connectivity... "
SSH_TEST_OUTPUT=$(ssh $SSH_OPTS -o BatchMode=yes "$SSH_CONNECTION" "echo SSH_OK" 2>&1) || true
if [[ "$SSH_TEST_OUTPUT" == *"SSH_OK"* ]]; then
echo -e "${GREEN}OK${NC}"
else
echo -e "${RED}FAILED${NC}"
echo -e "${RED}Cannot connect to $SSH_CONNECTION${NC}"
echo "SSH output: $SSH_TEST_OUTPUT"
echo ""
echo "Troubleshooting:"
echo " - Verify the hostname/IP is correct"
echo " - Check that your SSH key is added: ssh-add -l"
echo " - Try connecting manually: ssh -v $SSH_CONNECTION"
echo " - Check ~/.ssh/config for this host entry"
exit 1
fi
# Test 2: Does the WordPress path exist?
echo -n " Checking WordPress path ($WP_PATH)... "
REMOTE_CMD=$(build_remote_cmd "[ -d \"$WP_PATH\" ] && echo PATH_OK || echo PATH_MISSING")
PATH_TEST=$(ssh $SSH_OPTS "$SSH_CONNECTION" "$REMOTE_CMD" 2>&1) || true
if [[ "$PATH_TEST" == *"PATH_OK"* ]]; then
echo -e "${GREEN}OK${NC}"
else
echo -e "${RED}FAILED${NC}"
echo -e "${RED}Path '$WP_PATH' does not exist on $SSH_CONNECTION${NC}"
echo ""
echo "Troubleshooting — try: ssh $SSH_CONNECTION 'ls -la ~/'"
echo "Common WordPress paths:"
echo " /var/www/html (Generic Linux/Apache)"
echo " /var/www/html/wp (AWS subdirectory install)"
echo " /opt/bitnami/wordpress (AWS Bitnami/Lightsail)"
echo " /htdocs (Pressable)"
echo " ~/public_html (cPanel/SiteGround)"
exit 1
fi
# Test 3: Is WP-CLI available?
echo -n " Checking WP-CLI availability... "
REMOTE_CMD=$(build_remote_cmd "cd \"$WP_PATH\" && wp --version 2>&1")
WPCLI_TEST=$(ssh $SSH_OPTS "$SSH_CONNECTION" "$REMOTE_CMD" 2>&1) || true
if [[ "$WPCLI_TEST" == *"WP-CLI"* ]]; then
echo -e "${GREEN}OK (${WPCLI_TEST})${NC}"
else
echo -e "${RED}FAILED${NC}"
echo -e "${RED}WP-CLI is not available at $WP_PATH on $SSH_CONNECTION${NC}"
[ -n "$WPCLI_TEST" ] && echo "Output: $WPCLI_TEST"
echo ""
echo "Install WP-CLI on the remote server:"
echo " curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar"
echo " chmod +x wp-cli.phar"
echo " sudo mv wp-cli.phar /usr/local/bin/wp"
exit 1
fi
echo -e "${GREEN}All pre-flight checks passed.${NC}"
fi
#########################################
# Detect Permalink Structure
#########################################
echo -e "\n${YELLOW}Detecting permalink structure...${NC}"
if [ "$REMOTE_MODE" -eq 0 ]; then
PERMALINK_STRUCTURE=$(wp option get permalink_structure --allow-root 2>/dev/null || echo "")
HOME_URL=$(wp option get home --allow-root 2>/dev/null | sed 's|/$||' || echo "")
else
REMOTE_CMD=$(build_remote_cmd "cd \"$WP_PATH\" && wp option get permalink_structure --allow-root 2>/dev/null")
PERMALINK_STRUCTURE=$(ssh $SSH_OPTS "$SSH_CONNECTION" "$REMOTE_CMD" 2>"$SSH_STDERR" | tr -d '\r' || echo "")
REMOTE_CMD=$(build_remote_cmd "cd \"$WP_PATH\" && wp option get home --allow-root 2>/dev/null")
HOME_URL=$(ssh $SSH_OPTS "$SSH_CONNECTION" "$REMOTE_CMD" 2>"$SSH_STDERR" | tr -d '\r' | sed 's|/$||' || echo "")
fi
# Normalize: trim whitespace and carriage returns
PERMALINK_STRUCTURE=$(echo "$PERMALINK_STRUCTURE" | xargs 2>/dev/null || echo "")
echo " Permalink structure: ${PERMALINK_STRUCTURE:-'(default/plain)'}"
# If structure contains anything beyond %postname%, we need full permalink paths
# Simple structures: /%postname%/, /%post_id%/ — these don't need extra path resolution
if [[ -n "$PERMALINK_STRUCTURE" ]] && \
[[ "$PERMALINK_STRUCTURE" != "/%postname%/" ]] && \
[[ "$PERMALINK_STRUCTURE" != "/%postname%" ]] && \
[[ "$PERMALINK_STRUCTURE" != "/%post_id%/" ]]; then
EXPORT_PERMALINK_PATH=1
echo -e " ${YELLOW}Non-simple permalink structure detected — will export full permalink paths${NC}"
else
echo -e " ${GREEN}Simple permalink structure — standard URL construction will be used${NC}"
fi
#########################################
# Domain Input with History
#########################################
echo ""
# Get recent domains
RECENT_DOMAINS=()
RECENT_DOMAINS_INFO=()
while IFS='|' read -r domain last_export; do
if [ -n "$domain" ]; then
RECENT_DOMAINS+=("$domain")
RECENT_DOMAINS_INFO+=("$domain|$last_export")
fi
done < <(get_recent_domains)
if [ ${#RECENT_DOMAINS[@]} -gt 0 ]; then
echo -e "${YELLOW}Recent domains:${NC}"
for i in "${!RECENT_DOMAINS_INFO[@]}"; do
IFS='|' read -r domain last_export <<< "${RECENT_DOMAINS_INFO[$i]}"
echo " $((i+1)). $domain (last export: $last_export)"
done
echo ""
read -rp "Select a recent domain (1-${#RECENT_DOMAINS[@]}) or enter new domain: " DOMAIN_CHOICE
if [[ "$DOMAIN_CHOICE" =~ ^[1-9][0-9]*$ ]] && [ "$DOMAIN_CHOICE" -le "${#RECENT_DOMAINS[@]}" ]; then
BASE_DOMAIN="${RECENT_DOMAINS[$((DOMAIN_CHOICE-1))]}"
echo -e "${GREEN}Using: $BASE_DOMAIN${NC}"
else
BASE_DOMAIN="$DOMAIN_CHOICE"
fi
else
read -rp "Enter base domain: " BASE_DOMAIN
fi
BASE_DOMAIN=${BASE_DOMAIN:-example.com}
# Normalize domain: strip protocol prefix and trailing slashes
# Allows users to paste full URLs like https://example.com/blog/ and still get clean domain
BASE_DOMAIN=$(echo "$BASE_DOMAIN" | sed 's|^https\?://||' | sed 's|/*$||')
# Save domain to history immediately so it's not lost if the script fails later
add_domain_to_history "$BASE_DOMAIN"
read -rp "Include user export? (Y/n): " EXPORT_USERS
EXPORT_USERS=${EXPORT_USERS:-y}
# Create local directory with domain name
timestamp=$(date +"%Y%m%d_%H%M%S")
# Create sheet-friendly timestamp format
sheet_timestamp=$(date +"%Y-%m-%d_%H%M%S")
# Sanitize domain name for filesystem and Excel sheet names
# Replace . / : with dashes (colon is invalid in Excel sheet titles)
DOMAIN_SAFE=$(echo "$BASE_DOMAIN" | tr './:' '-' | tr '[:upper:]' '[:lower:]')
EXPORT_DIR="!export_wp_posts_${timestamp}_${DOMAIN_SAFE}"
mkdir -p "$EXPORT_DIR"
# Define file paths
ALL_POSTS_FILE="$EXPORT_DIR/export_all_posts.csv"
CUSTOM_PERMALINKS_FILE="$EXPORT_DIR/export_custom_permalinks.csv"
PERMALINK_PATH_FILE="$EXPORT_DIR/export_permalink_paths.csv"
TEMP_FILE="$EXPORT_DIR/export_wp_posts_temp.csv"
VALIDATED_FILE="$EXPORT_DIR/export_wp_posts_validated.csv"
FINAL_CSV_FILE="$EXPORT_DIR/export_wp_posts_${timestamp}.csv"
EXCEL_FILE="$EXPORT_DIR/export_wp_posts_${timestamp}.xlsx"
DEBUG_FILE="$EXPORT_DIR/export_debug_log.txt"
# Clear previous export files
> "$ALL_POSTS_FILE"
> "$CUSTOM_PERMALINKS_FILE"
[ "$EXPORT_PERMALINK_PATH" -eq 1 ] && > "$PERMALINK_PATH_FILE"
[ "$DEBUG" -eq 1 ] && > "$DEBUG_FILE"
echo -e "\n${YELLOW}Discovering post types...${NC}"
#########################################
# Discover Post Types
#########################################
# Initialize POST_TYPES array
POST_TYPES=()
if [ "$REMOTE_MODE" -eq 0 ]; then
# Local discovery - simpler and more reliable
echo "Discovering post types locally..."
POST_TYPES=($(wp post-type list --fields=name,public --allow-root --format=csv | tail -n +2 | awk -F, '$2=="1" && $1!="attachment" {print $1}'))
if [ ${#POST_TYPES[@]} -gt 0 ]; then
echo -e "${GREEN}✓ Discovered ${#POST_TYPES[@]} post types${NC}"
else
echo -e "${YELLOW}No public post types found. Using defaults.${NC}"
POST_TYPES=("post" "page")
fi
else
# Remote discovery - try multiple methods
echo "Attempting to discover post types remotely..."
# Method 1: Simple approach
echo "Method 1: Trying standard discovery..."
REMOTE_CMD=$(build_remote_cmd "cd \"$WP_PATH\" && wp post-type list --field=name --public=true --format=csv 2>/dev/null")
[ "$VERBOSE" -eq 1 ] && echo -e " ${YELLOW}[SSH] $REMOTE_CMD${NC}"
POST_TYPES_RAW=$(ssh $SSH_OPTS "$SSH_CONNECTION" "$REMOTE_CMD" 2>"$SSH_STDERR" || echo "")
# Clean output — filter SSH noise, || true prevents grep exit code 1 from killing script via pipefail
POST_TYPES_RAW=$(echo "$POST_TYPES_RAW" | tr -d '\r' | grep -v "^$" | grep -v "^Connection to" | grep -v "^Warning:" | grep -v "^Pseudo-terminal" || true)
[ "$VERBOSE" -eq 1 ] && echo " [DEBUG] Method 1 raw output: '$POST_TYPES_RAW'"
if [ -z "$POST_TYPES_RAW" ] || [[ "$POST_TYPES_RAW" == *"Error"* ]]; then
echo "Method 2: Trying with simpler format..."
REMOTE_CMD=$(build_remote_cmd "cd \"$WP_PATH\" && wp post-type list --field=name 2>/dev/null | grep -v attachment")
[ "$VERBOSE" -eq 1 ] && echo -e " ${YELLOW}[SSH] $REMOTE_CMD${NC}"
POST_TYPES_RAW=$(ssh $SSH_OPTS "$SSH_CONNECTION" "$REMOTE_CMD" 2>"$SSH_STDERR" || echo "")
POST_TYPES_RAW=$(echo "$POST_TYPES_RAW" | tr -d '\r' | grep -v "^$" || true)
[ "$VERBOSE" -eq 1 ] && echo " [DEBUG] Method 2 raw output: '$POST_TYPES_RAW'"
fi
if [ -z "$POST_TYPES_RAW" ] || [[ "$POST_TYPES_RAW" == *"Error"* ]]; then
echo "Method 3: Trying PHP evaluation..."
REMOTE_CMD=$(build_remote_cmd "cd \"$WP_PATH\" && wp eval 'foreach(get_post_types(array(\"public\"=>true)) as \$t) if(\$t!=\"attachment\") echo \$t.\"\n\";'")
[ "$VERBOSE" -eq 1 ] && echo -e " ${YELLOW}[SSH] $REMOTE_CMD${NC}"
POST_TYPES_RAW=$(ssh $SSH_OPTS "$SSH_CONNECTION" "$REMOTE_CMD" 2>"$SSH_STDERR" || echo "")
POST_TYPES_RAW=$(echo "$POST_TYPES_RAW" | tr -d '\r' | grep -v "^$" || true)
[ "$VERBOSE" -eq 1 ] && echo " [DEBUG] Method 3 raw output: '$POST_TYPES_RAW'"
fi
if [ -n "$POST_TYPES_RAW" ] && [[ "$POST_TYPES_RAW" != *"closed"* ]] && [[ "$POST_TYPES_RAW" != *"Error"* ]]; then
# Parse discovered post types
while IFS= read -r type; do
type=$(echo "$type" | xargs)
if [ -n "$type" ] && [[ ! "$type" =~ ^(name|attachment)$ ]] && [[ "$type" != "name" ]]; then
POST_TYPES+=("$type")
fi
done <<< "$POST_TYPES_RAW"
if [ ${#POST_TYPES[@]} -gt 0 ]; then
echo -e "${GREEN}✓ Discovered ${#POST_TYPES[@]} post types automatically${NC}"
else
echo -e "${YELLOW}Discovery returned no valid post types${NC}"
fi
else
echo -e "${YELLOW}Auto-discovery failed. Will use manual entry.${NC}"
fi
# If we still don't have post types, fall back to manual
if [ ${#POST_TYPES[@]} -eq 0 ]; then
echo "Using standard WordPress post types as base..."
POST_TYPES=("post" "page")
echo -e "\n${YELLOW}Tip: You can check post types manually by SSHing in and running:${NC}"
echo " wp post-type list --public=true"
echo ""
read -rp "Do you know your custom post types? (y/n): " ADD_CUSTOM
if [[ "$ADD_CUSTOM" == "y" || "$ADD_CUSTOM" == "Y" ]]; then
echo "Enter post types one per line (press Enter twice when done):"
echo "Example: commercial, article, press_release, etc."
while true; do
read -rp "> " type
if [ -z "$type" ]; then
break
fi
type=$(echo "$type" | xargs | tr -d ',')
if [ -n "$type" ] && [[ ! " ${POST_TYPES[@]} " =~ " ${type} " ]]; then
POST_TYPES+=("$type")
echo " Added: $type"
fi
done
fi
fi
fi
# Ensure we have at least some post types
if [ ${#POST_TYPES[@]} -eq 0 ]; then
echo -e "${RED}Error: No post types defined. Using defaults.${NC}"
POST_TYPES=("post" "page")
fi
echo "Will export post types: ${POST_TYPES[*]}"
# Create a comma-separated list for user post counts
POST_TYPES_LIST=$(IFS=,; echo "${POST_TYPES[*]}")
#########################################
# Custom Meta Fields
#########################################
CUSTOM_META_KEYS=()
META_FILES=()
# Check for previously used meta keys for this domain
SAVED_META_KEYS=()
while IFS= read -r key; do
if [ -n "$key" ]; then
SAVED_META_KEYS+=("$key")
fi
done < <(get_domain_meta_keys "$BASE_DOMAIN")
echo ""
if [ ${#SAVED_META_KEYS[@]} -gt 0 ]; then
echo -e "${YELLOW}Previous meta fields for $BASE_DOMAIN:${NC} ${SAVED_META_KEYS[*]}"
read -rp "Use previous meta fields? (Y/n): " USE_SAVED_META
if [[ "$USE_SAVED_META" != "n" && "$USE_SAVED_META" != "N" ]]; then
CUSTOM_META_KEYS=("${SAVED_META_KEYS[@]}")
echo -e "${GREEN}Using saved meta fields: ${CUSTOM_META_KEYS[*]}${NC}"
read -rp "Add more meta fields? (y/N): " ADD_MORE_META
if [[ "$ADD_MORE_META" == "y" || "$ADD_MORE_META" == "Y" ]]; then
echo "Enter additional meta key names one per line (press Enter twice when done):"
while true; do
read -rp "> " meta_key
if [ -z "$meta_key" ]; then
break
fi
meta_key=$(echo "$meta_key" | xargs | tr -d ',')
if [ -n "$meta_key" ] && [[ ! " ${CUSTOM_META_KEYS[*]+${CUSTOM_META_KEYS[*]}} " =~ " ${meta_key} " ]]; then
CUSTOM_META_KEYS+=("$meta_key")
echo " Added: $meta_key"
fi
done
fi
else
read -rp "Export additional meta fields? (y/N): " ADD_META
if [[ "$ADD_META" == "y" || "$ADD_META" == "Y" ]]; then
echo "Enter meta key names one per line (press Enter twice when done):"
echo "Example: _custom_clean_url, _yoast_wpseo_title"
while true; do
read -rp "> " meta_key
if [ -z "$meta_key" ]; then
break
fi
meta_key=$(echo "$meta_key" | xargs | tr -d ',')
if [ -n "$meta_key" ] && [[ ! " ${CUSTOM_META_KEYS[*]+${CUSTOM_META_KEYS[*]}} " =~ " ${meta_key} " ]]; then
CUSTOM_META_KEYS+=("$meta_key")
echo " Added: $meta_key"
fi
done
fi
fi
else
read -rp "Export additional meta fields? (y/N): " ADD_META
if [[ "$ADD_META" == "y" || "$ADD_META" == "Y" ]]; then
echo "Enter meta key names one per line (press Enter twice when done):"
echo "Example: _custom_clean_url, _yoast_wpseo_title"
while true; do
read -rp "> " meta_key
if [ -z "$meta_key" ]; then
break
fi
meta_key=$(echo "$meta_key" | xargs | tr -d ',')
if [ -n "$meta_key" ] && [[ ! " ${CUSTOM_META_KEYS[*]+${CUSTOM_META_KEYS[*]}} " =~ " ${meta_key} " ]]; then
CUSTOM_META_KEYS+=("$meta_key")
echo " Added: $meta_key"
fi
done
fi
fi
# Save meta keys for this domain (if any were selected)
if [ ${#CUSTOM_META_KEYS[@]} -gt 0 ]; then
save_domain_meta_keys "$BASE_DOMAIN" "${CUSTOM_META_KEYS[@]}"
echo -e "${GREEN}Will export meta fields: ${CUSTOM_META_KEYS[*]}${NC}"
fi
# Dynamic column count: 7 base columns + number of custom meta fields
EXPECTED_COLUMNS=$((7 + EXPORT_PERMALINK_PATH + ${#CUSTOM_META_KEYS[@]}))
#########################################
# Export Posts and Custom Permalink Data
#########################################
# Export posts with all required fields
echo "ID,post_title,post_name,post_date,post_status,post_type" > "$ALL_POSTS_FILE"
echo -e "\n${YELLOW}Exporting all posts...${NC}"
if [ "$REMOTE_MODE" -eq 1 ]; then
echo "Note: Remote hosts may close connections during large exports. This is normal."
fi
FIRST=1
for post_type in "${POST_TYPES[@]}"; do
echo " Exporting post type: $post_type"
if [ "$REMOTE_MODE" -eq 0 ]; then
# Local export