-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathPost_Block_Command.php
More file actions
1844 lines (1679 loc) · 51.6 KB
/
Post_Block_Command.php
File metadata and controls
1844 lines (1679 loc) · 51.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
<?php
use Mustangostang\Spyc;
use WP_CLI\Entity\Block_HTML_Sync_Filters;
use WP_CLI\Entity\Block_Processor_Helper;
use WP_CLI\Formatter;
use WP_CLI\Fetchers\Post as PostFetcher;
use WP_CLI\Utils;
/**
* Manages blocks within post content.
*
* Provides commands for inspecting, manipulating, and managing
* Gutenberg blocks in post content.
*
* ## EXAMPLES
*
* # List all blocks in a post.
* $ wp post block list 123
* +------------------+-------+
* | blockName | count |
* +------------------+-------+
* | core/paragraph | 2 |
* | core/heading | 1 |
* +------------------+-------+
*
* # Parse blocks in a post to JSON.
* $ wp post block parse 123 --format=json
*
* # Insert a paragraph block.
* $ wp post block insert 123 core/paragraph --content="Hello World"
*
* @package wp-cli
*
* @phpstan-type ParsedBlock array{blockName?: string, attrs: array<string, mixed>, innerBlocks: array<array<mixed>>, innerHTML: string, innerContent: list<mixed>}
* @phpstan-type ParsedBlockWithBlockName array{blockName: string, attrs: array<string, mixed>, innerBlocks: array<array<mixed>>, innerHTML: string, innerContent: list<mixed>}
*/
class Post_Block_Command extends WP_CLI_Command {
/**
* @var PostFetcher
*/
private $fetcher;
/**
* Whether filters have been registered.
*
* @var bool
*/
private static $filters_registered = false;
/**
* Default fields to display for block list.
*
* @var string[]
*/
protected $obj_fields = [
'index',
'blockName',
'attrs',
];
public function __construct() {
$this->fetcher = new PostFetcher();
// Register default HTML sync filters once.
if ( ! self::$filters_registered ) {
Block_HTML_Sync_Filters::register();
self::$filters_registered = true;
}
}
/**
* Gets a single block by index.
*
* Retrieves the full structure of a block at the specified position.
*
* ## OPTIONS
*
* <id>
* : The ID of the post.
*
* <index>
* : The block index (0-indexed).
*
* [--raw]
* : Include innerHTML in output.
*
* [--format=<format>]
* : Render output in a particular format.
* ---
* default: json
* options:
* - json
* - yaml
* ---
*
* ## EXAMPLES
*
* # Get the first block in a post.
* $ wp post block get 123 0
* {
* "blockName": "core/paragraph",
* "attrs": {},
* "innerBlocks": []
* }
*
* # Get the third block (index 2) with attributes.
* $ wp post block get 123 2
* {
* "blockName": "core/heading",
* "attrs": {
* "level": 2
* },
* "innerBlocks": []
* }
*
* # Get block as YAML format.
* $ wp post block get 123 1 --format=yaml
* blockName: core/image
* attrs:
* id: 456
* sizeSlug: large
* innerBlocks: []
*
* # Get block with raw HTML content included.
* $ wp post block get 123 0 --raw
* {
* "blockName": "core/paragraph",
* "attrs": {},
* "innerBlocks": [],
* "innerHTML": "<p>Hello World</p>",
* "innerContent": ["<p>Hello World</p>"]
* }
*
* @subcommand get
*/
public function get( $args, $assoc_args ) {
$post = $this->fetcher->get_check( $args[0] );
$index = (int) $args[1];
// Use streaming helper to get block at index.
$block = Block_Processor_Helper::get_at_index( $post->post_content, $index );
if ( null === $block ) {
$block_count = Block_Processor_Helper::get_block_count( $post->post_content );
WP_CLI::error( "Invalid index: {$index}. Post has {$block_count} block(s) (0-indexed)." );
}
$include_raw = Utils\get_flag_value( $assoc_args, 'raw', false );
if ( ! $include_raw ) {
$block = Block_Processor_Helper::strip_inner_html( [ $block ] )[0];
}
$format = Utils\get_flag_value( $assoc_args, 'format', 'json' );
if ( 'yaml' === $format ) {
echo Spyc::YAMLDump( $block, 2, 0, true );
} else {
// phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
echo json_encode( $block, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) . "\n";
}
}
/**
* Updates a block's attributes or content by index.
*
* Modifies a specific block without changing its type. For blocks where
* attributes are reflected in HTML (like heading levels), the HTML is
* automatically updated to match the new attributes.
*
* ## OPTIONS
*
* <id>
* : The ID of the post.
*
* <index>
* : The block index to update (0-indexed).
*
* [--attrs=<attrs>]
* : Block attributes as JSON. Merges with existing attributes by default.
*
* [--content=<content>]
* : New innerHTML content for the block.
*
* [--replace-attrs]
* : Replace all attributes instead of merging.
*
* [--porcelain]
* : Output just the post ID.
*
* ## EXAMPLES
*
* # Change a heading from h2 to h3.
* $ wp post block update 123 0 --attrs='{"level":3}'
* Success: Updated block at index 0 in post 123.
*
* # Add alignment to an existing paragraph (merges with existing attrs).
* $ wp post block update 123 1 --attrs='{"align":"center"}'
* Success: Updated block at index 1 in post 123.
*
* # Update the text content of a paragraph block.
* $ wp post block update 123 2 --content="<p>Updated paragraph text</p>"
* Success: Updated block at index 2 in post 123.
*
* # Update both attributes and content at once.
* $ wp post block update 123 0 --attrs='{"level":2}' --content="<h2>New Heading</h2>"
* Success: Updated block at index 0 in post 123.
*
* # Replace all attributes instead of merging (removes existing attrs).
* $ wp post block update 123 0 --attrs='{"level":4}' --replace-attrs
* Success: Updated block at index 0 in post 123.
*
* # Get just the post ID for scripting.
* $ wp post block update 123 0 --attrs='{"level":2}' --porcelain
* 123
*
* # Use custom HTML sync logic via the wp_cli_post_block_update_html filter.
* # Use WP_CLI::add_wp_hook() in a file loaded with --require.
* $ wp post block update 123 0 --attrs='{"url":"https://example.com"}' --require=my-sync-filters.php
* Success: Updated block at index 0 in post 123.
*
* @subcommand update
*/
public function update( $args, $assoc_args ) {
$post = $this->fetcher->get_check( $args[0] );
$index = (int) $args[1];
$blocks = parse_blocks( $post->post_content );
// Filter out empty blocks but keep track of original indices.
$filtered_blocks = [];
$index_map = [];
foreach ( $blocks as $original_idx => $block ) {
if ( ! empty( $block['blockName'] ) ) {
$index_map[ count( $filtered_blocks ) ] = $original_idx;
$filtered_blocks[] = $block;
}
}
if ( $index < 0 || $index >= count( $filtered_blocks ) ) {
WP_CLI::error( "Invalid index: {$index}. Post has " . count( $filtered_blocks ) . ' block(s) (0-indexed).' );
}
$original_idx = $index_map[ $index ];
$block = $blocks[ $original_idx ];
$attrs_json = Utils\get_flag_value( $assoc_args, 'attrs', null );
$content = Utils\get_flag_value( $assoc_args, 'content', null );
$replace_attrs = Utils\get_flag_value( $assoc_args, 'replace-attrs', false );
if ( null === $attrs_json && null === $content ) {
WP_CLI::error( 'You must specify either --attrs or --content.' );
}
if ( null !== $attrs_json ) {
$new_attrs = json_decode( $attrs_json, true );
if ( ! is_array( $new_attrs ) ) {
WP_CLI::error( 'Invalid JSON provided for --attrs. Must be a JSON object.' );
}
if ( $replace_attrs ) {
$block['attrs'] = $new_attrs;
} else {
$block['attrs'] = array_merge(
is_array( $block['attrs'] ) ? $block['attrs'] : [],
$new_attrs
);
}
// Update HTML to reflect attribute changes for known block types.
$block = $this->sync_html_with_attrs( $block, $new_attrs );
}
if ( null !== $content ) {
$block['innerHTML'] = $content;
$block['innerContent'] = [ $content ];
}
$blocks[ $original_idx ] = $block;
// @phpstan-ignore argument.type
$new_content = serialize_blocks( $blocks );
$result = wp_update_post(
[
'ID' => $post->ID,
'post_content' => $new_content,
],
true
);
if ( is_wp_error( $result ) ) {
WP_CLI::error( $result->get_error_message() );
}
if ( Utils\get_flag_value( $assoc_args, 'porcelain' ) ) {
WP_CLI::line( (string) $post->ID );
} else {
WP_CLI::success( "Updated block at index {$index} in post {$post->ID}." );
}
}
/**
* Moves a block from one position to another.
*
* Reorders blocks within the post by moving a block from one index to another.
*
* ## OPTIONS
*
* <id>
* : The ID of the post.
*
* <from-index>
* : Current block index (0-indexed).
*
* <to-index>
* : Target position index (0-indexed).
*
* [--porcelain]
* : Output just the post ID.
*
* ## EXAMPLES
*
* # Move the first block to the third position.
* $ wp post block move 123 0 2
* Success: Moved block from index 0 to index 2 in post 123.
*
* # Move the last block (index 4) to the beginning.
* $ wp post block move 123 4 0
* Success: Moved block from index 4 to index 0 in post 123.
*
* # Move a heading block from position 3 to position 1.
* $ wp post block move 123 3 1
* Success: Moved block from index 3 to index 1 in post 123.
*
* # Move block and get post ID for scripting.
* $ wp post block move 123 2 0 --porcelain
* 123
*
* @subcommand move
*/
public function move( $args, $assoc_args ) {
$post = $this->fetcher->get_check( $args[0] );
$from_index = (int) $args[1];
$to_index = (int) $args[2];
$blocks = parse_blocks( $post->post_content );
// Filter out empty blocks but keep track of original indices.
$filtered_blocks = [];
$index_map = [];
foreach ( $blocks as $original_idx => $block ) {
if ( ! empty( $block['blockName'] ) ) {
$index_map[ count( $filtered_blocks ) ] = $original_idx;
$filtered_blocks[] = $block;
}
}
$block_count = count( $filtered_blocks );
if ( $from_index < 0 || $from_index >= $block_count ) {
WP_CLI::error( "Invalid from-index: {$from_index}. Post has {$block_count} block(s) (0-indexed)." );
}
if ( $to_index < 0 || $to_index >= $block_count ) {
WP_CLI::error( "Invalid to-index: {$to_index}. Post has {$block_count} block(s) (0-indexed)." );
}
if ( $from_index === $to_index ) {
WP_CLI::warning( 'Source and destination indices are the same. No changes made.' );
return;
}
// Work with the actual blocks array (including whitespace).
$original_from = (int) $index_map[ $from_index ];
$block_to_move = $blocks[ $original_from ];
// Remove the block from original position.
array_splice( $blocks, $original_from, 1 );
// Recalculate index map after removal.
$new_filtered = [];
$new_index_map = [];
foreach ( $blocks as $idx => $block ) {
if ( ! empty( $block['blockName'] ) ) {
$new_index_map[ count( $new_filtered ) ] = (int) $idx;
$new_filtered[] = $block;
}
}
// Calculate the actual insertion position.
if ( $to_index >= count( $new_filtered ) ) {
// Insert at end.
$insert_pos = count( $blocks );
} else {
$insert_pos = (int) $new_index_map[ $to_index ];
}
// Insert at new position.
array_splice( $blocks, $insert_pos, 0, [ $block_to_move ] );
$new_content = serialize_blocks( $blocks );
$result = wp_update_post(
[
'ID' => $post->ID,
'post_content' => $new_content,
],
true
);
if ( is_wp_error( $result ) ) {
WP_CLI::error( $result->get_error_message() );
}
if ( Utils\get_flag_value( $assoc_args, 'porcelain' ) ) {
WP_CLI::line( (string) $post->ID );
} else {
WP_CLI::success( "Moved block from index {$from_index} to index {$to_index} in post {$post->ID}." );
}
}
/**
* Exports block content to a file.
*
* Exports blocks from a post to a file for backup or migration.
*
* ## OPTIONS
*
* <id>
* : The ID of the post to export blocks from.
*
* [--file=<file>]
* : Output file path. If not specified, outputs to STDOUT.
*
* [--format=<format>]
* : Export format.
* ---
* default: json
* options:
* - json
* - yaml
* - html
* ---
*
* [--raw]
* : Include innerHTML in JSON/YAML output.
*
* ## EXAMPLES
*
* # Export blocks to a JSON file for backup.
* $ wp post block export 123 --file=blocks.json
* Success: Exported 5 blocks to blocks.json
*
* # Export blocks to STDOUT as JSON.
* $ wp post block export 123
* {
* "version": "1.0",
* "generator": "wp-cli/entity-command",
* "post_id": 123,
* "exported_at": "2024-12-10T12:00:00+00:00",
* "blocks": [...]
* }
*
* # Export as YAML format.
* $ wp post block export 123 --format=yaml
* version: "1.0"
* generator: wp-cli/entity-command
* blocks:
* - blockName: core/paragraph
* attrs: []
*
* # Export rendered HTML (final output, not block structure).
* $ wp post block export 123 --format=html --file=content.html
* Success: Exported 5 blocks to content.html
*
* # Export with raw innerHTML included for complete backup.
* $ wp post block export 123 --raw --file=blocks-full.json
* Success: Exported 5 blocks to blocks-full.json
*
* # Pipe export to another command.
* $ wp post block export 123 | jq '.blocks[].blockName'
*
* @subcommand export
*/
public function export( $args, $assoc_args ) {
$post = $this->fetcher->get_check( $args[0] );
$file = Utils\get_flag_value( $assoc_args, 'file', null );
$format = Utils\get_flag_value( $assoc_args, 'format', 'json' );
$include_raw = Utils\get_flag_value( $assoc_args, 'raw', false );
$blocks = parse_blocks( $post->post_content );
// Filter out empty blocks.
$blocks = array_values(
array_filter(
$blocks,
function ( $block ) {
return ! empty( $block['blockName'] );
}
)
);
$block_count = count( $blocks );
if ( 'html' === $format ) {
$output = '';
foreach ( $blocks as $block ) {
$output .= render_block( $block );
}
} else {
if ( ! $include_raw ) {
$blocks = $this->strip_inner_html( $blocks );
}
$export_data = [
'version' => '1.0',
'generator' => 'wp-cli/entity-command',
'post_id' => $post->ID,
'exported_at' => gmdate( 'c' ),
'blocks' => $blocks,
];
if ( 'yaml' === $format ) {
$output = Spyc::YAMLDump( $export_data, 2, 0, true );
} else {
// phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode
$output = json_encode( $export_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) . "\n";
}
}
if ( null !== $file ) {
$dir = dirname( $file );
if ( ! empty( $dir ) && ! is_dir( $dir ) ) {
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir
if ( ! mkdir( $dir, 0755, true ) ) {
WP_CLI::error( "Could not create directory: {$dir}" );
}
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
$result = file_put_contents( $file, $output );
if ( false === $result ) {
WP_CLI::error( "Could not write to file: {$file}" );
}
$block_word = 1 === $block_count ? 'block' : 'blocks';
WP_CLI::success( "Exported {$block_count} {$block_word} to {$file}" );
} else {
echo $output;
}
}
/**
* Imports blocks from a file into a post.
*
* Imports blocks from a JSON or YAML file into a post's content.
*
* ## OPTIONS
*
* <id>
* : The ID of the post to import blocks into.
*
* [--file=<file>]
* : Input file path. If not specified, reads from STDIN.
*
* [--position=<position>]
* : Where to insert imported blocks. Accepts 'start', 'end', or a numeric index.
* ---
* default: end
* ---
*
* [--replace]
* : Replace all existing blocks instead of appending.
*
* [--porcelain]
* : Output just the number of blocks imported.
*
* ## EXAMPLES
*
* # Import blocks from a JSON file, append to end of post.
* $ wp post block import 123 --file=blocks.json
* Success: Imported 5 blocks into post 123.
*
* # Import blocks at the beginning of the post.
* $ wp post block import 123 --file=blocks.json --position=start
* Success: Imported 5 blocks into post 123.
*
* # Replace all existing content with imported blocks.
* $ wp post block import 123 --file=blocks.json --replace
* Success: Imported 5 blocks into post 123.
*
* # Import from STDIN (piped from another command).
* $ cat blocks.json | wp post block import 123
* Success: Imported 5 blocks into post 123.
*
* # Copy blocks from one post to another.
* $ wp post block export 123 | wp post block import 456
* Success: Imported 5 blocks into post 456.
*
* # Import YAML format.
* $ wp post block import 123 --file=blocks.yaml
* Success: Imported 3 blocks into post 123.
*
* # Get just the count of imported blocks for scripting.
* $ wp post block import 123 --file=blocks.json --porcelain
* 5
*
* @subcommand import
*/
public function import( $args, $assoc_args ) {
$post = $this->fetcher->get_check( $args[0] );
$file = Utils\get_flag_value( $assoc_args, 'file', null );
$position = Utils\get_flag_value( $assoc_args, 'position', 'end' );
$replace = Utils\get_flag_value( $assoc_args, 'replace', false );
if ( null !== $file ) {
if ( ! file_exists( $file ) ) {
WP_CLI::error( "File not found: {$file}" );
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$input = file_get_contents( $file );
} else {
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$input = file_get_contents( 'php://stdin' );
}
if ( false === $input || '' === trim( $input ) ) {
WP_CLI::error( 'No input data provided.' );
}
// Try to parse as JSON first, then YAML.
$data = json_decode( $input, true );
if ( null === $data ) {
$data = Spyc::YAMLLoadString( $input );
}
if ( ! is_array( $data ) ) {
WP_CLI::error( 'Invalid input format. Expected JSON or YAML.' );
}
// Handle export format (with metadata wrapper) or plain blocks array.
$import_blocks = isset( $data['blocks'] ) ? $data['blocks'] : $data;
if ( ! is_array( $import_blocks ) ) {
WP_CLI::error( 'No blocks found in import data.' );
}
/**
* @phpstan-var array<int|string, ParsedBlock> $import_blocks
*/
// Validate block structure.
foreach ( $import_blocks as $idx => $block ) {
if ( ! isset( $block['blockName'] ) ) {
WP_CLI::error( "Invalid block structure at index {$idx}: missing blockName." );
}
}
/**
* @phpstan-var array<int|string, ParsedBlockWithBlockName> $import_blocks
*/
$imported_count = count( $import_blocks );
if ( $replace ) {
$blocks = $import_blocks;
} else {
$blocks = parse_blocks( $post->post_content );
// Filter out empty blocks.
$blocks = array_values(
array_filter(
$blocks,
function ( $block ) {
return ! empty( $block['blockName'] );
}
)
);
if ( 'start' === $position ) {
$blocks = array_merge( $import_blocks, $blocks );
} elseif ( 'end' === $position ) {
$blocks = array_merge( $blocks, $import_blocks );
} elseif ( is_numeric( $position ) ) {
$pos = (int) $position;
if ( $pos < 0 || $pos > count( $blocks ) ) {
WP_CLI::error( "Invalid position: {$pos}. Post has " . count( $blocks ) . ' block(s) (0-indexed).' );
}
array_splice( $blocks, $pos, 0, $import_blocks );
} else {
$blocks = array_merge( $blocks, $import_blocks );
}
}
$new_content = serialize_blocks( $blocks );
$result = wp_update_post(
[
'ID' => $post->ID,
'post_content' => $new_content,
],
true
);
if ( is_wp_error( $result ) ) {
WP_CLI::error( $result->get_error_message() );
}
if ( Utils\get_flag_value( $assoc_args, 'porcelain' ) ) {
WP_CLI::line( (string) $imported_count );
} else {
$block_word = 1 === $imported_count ? 'block' : 'blocks';
WP_CLI::success( "Imported {$imported_count} {$block_word} into post {$post->ID}." );
}
}
/**
* Counts blocks across multiple posts.
*
* Analyzes block usage across posts for site-wide reporting.
*
* ## OPTIONS
*
* [<id>...]
* : Optional post IDs. If not specified, queries all posts.
*
* [--block=<block-name>]
* : Only count specific block type.
*
* [--post-type=<type>]
* : Limit to specific post type(s). Comma-separated.
* ---
* default: post,page
* ---
*
* [--post-status=<status>]
* : Post status to include.
* ---
* default: publish
* ---
*
* [--format=<format>]
* : Output format.
* ---
* default: table
* options:
* - table
* - json
* - csv
* - yaml
* - count
* ---
*
* ## EXAMPLES
*
* # Count all blocks across published posts and pages.
* $ wp post block count
* +------------------+-------+-------+
* | blockName | count | posts |
* +------------------+-------+-------+
* | core/paragraph | 1542 | 234 |
* | core/heading | 523 | 198 |
* | core/image | 312 | 156 |
* +------------------+-------+-------+
*
* # Count blocks in specific posts only.
* $ wp post block count 123 456 789
* +------------------+-------+-------+
* | blockName | count | posts |
* +------------------+-------+-------+
* | core/paragraph | 8 | 3 |
* | core/heading | 3 | 2 |
* +------------------+-------+-------+
*
* # Count only paragraph blocks across the site.
* $ wp post block count --block=core/paragraph --format=count
* 1542
*
* # Count blocks in a custom post type.
* $ wp post block count --post-type=product
*
* # Count blocks in multiple post types.
* $ wp post block count --post-type=post,page,product
*
* # Count blocks including drafts.
* $ wp post block count --post-status=draft
*
* # Get count as JSON for further processing.
* $ wp post block count --format=json
* [{"blockName":"core/paragraph","count":1542,"posts":234}]
*
* # Get total number of unique block types used.
* $ wp post block count --format=count
* 15
*
* @subcommand count
*/
public function count( $args, $assoc_args ) {
$block_filter = Utils\get_flag_value( $assoc_args, 'block', null );
$post_types = Utils\get_flag_value( $assoc_args, 'post-type', 'post,page' );
$post_status = Utils\get_flag_value( $assoc_args, 'post-status', 'publish' );
$format = Utils\get_flag_value( $assoc_args, 'format', 'table' );
if ( ! empty( $args ) ) {
$post_ids = array_map( 'intval', $args );
} else {
$query_args = [
'post_type' => explode( ',', $post_types ),
'post_status' => $post_status,
'posts_per_page' => -1,
'fields' => 'ids',
];
$post_ids = get_posts( $query_args );
}
if ( empty( $post_ids ) ) {
WP_CLI::warning( 'No posts found matching criteria.' );
return;
}
$block_counts = [];
$post_counts = [];
foreach ( $post_ids as $post_id ) {
$post = get_post( $post_id );
if ( ! $post || ! has_blocks( $post->post_content ) ) {
continue;
}
$blocks = parse_blocks( $post->post_content );
$this->aggregate_block_counts( $blocks, $block_counts, $post_counts, $post_id, $block_filter );
}
if ( empty( $block_counts ) ) {
WP_CLI::warning( 'No blocks found in queried posts.' );
return;
}
// Sort by count descending.
arsort( $block_counts );
// Handle single block filter with count format.
if ( null !== $block_filter && 'count' === $format ) {
$count = isset( $block_counts[ $block_filter ] ) ? $block_counts[ $block_filter ] : 0;
WP_CLI::line( (string) $count );
return;
}
$items = [];
foreach ( $block_counts as $block_name => $count ) {
$items[] = [
'blockName' => $block_name,
'count' => $count,
'posts' => isset( $post_counts[ $block_name ] ) ? count( $post_counts[ $block_name ] ) : 0,
];
}
if ( 'count' === $format ) {
WP_CLI::line( (string) count( $items ) );
return;
}
$formatter = new Formatter( $assoc_args, [ 'blockName', 'count', 'posts' ] );
$formatter->display_items( $items );
}
/**
* Clones a block within a post.
*
* Duplicates an existing block and inserts it at a specified position.
*
* ## OPTIONS
*
* <id>
* : The ID of the post.
*
* <source-index>
* : Index of the block to clone (0-indexed).
*
* [--position=<position>]
* : Where to insert the cloned block. Accepts 'after', 'before', 'start', 'end', or a numeric index.
* ---
* default: after
* ---
*
* [--porcelain]
* : Output just the new block index.
*
* ## EXAMPLES
*
* # Clone a block and insert immediately after it (default).
* $ wp post block clone 123 2
* Success: Cloned block to index 3 in post 123.
*
* # Clone the first block and insert immediately before it.
* $ wp post block clone 123 0 --position=before
* Success: Cloned block to index 0 in post 123.
*
* # Clone a block and insert at the end of the post.
* $ wp post block clone 123 0 --position=end
* Success: Cloned block to index 5 in post 123.
*
* # Clone a block and insert at the start of the post.
* $ wp post block clone 123 3 --position=start
* Success: Cloned block to index 0 in post 123.
*
* # Clone and get just the new block index for scripting.
* $ wp post block clone 123 1 --porcelain
* 2
*
* # Duplicate the hero section (first block) at the end for a footer.
* $ wp post block clone 123 0 --position=end
* Success: Cloned block to index 10 in post 123.
*
* @subcommand clone
*/
public function clone_block( $args, $assoc_args ) {
$post = $this->fetcher->get_check( $args[0] );
$source_index = (int) $args[1];
$position = Utils\get_flag_value( $assoc_args, 'position', 'after' );
$blocks = parse_blocks( $post->post_content );
// Filter out empty blocks but keep track of original indices.
$filtered_blocks = [];
$index_map = [];
foreach ( $blocks as $original_idx => $block ) {
if ( ! empty( $block['blockName'] ) ) {
$index_map[ count( $filtered_blocks ) ] = $original_idx;
$filtered_blocks[] = $block;
}
}
$block_count = count( $filtered_blocks );
if ( $source_index < 0 || $source_index >= $block_count ) {
WP_CLI::error( "Invalid source-index: {$source_index}. Post has {$block_count} block(s) (0-indexed)." );
}
$original_idx = (int) $index_map[ $source_index ];
$cloned_block = $this->deep_copy_block( $blocks[ $original_idx ] );
// Calculate insertion position.
if ( is_numeric( $position ) ) {
$new_index = (int) $position;
if ( $new_index < 0 || $new_index > $block_count ) {
WP_CLI::error( "Invalid position: {$new_index}. Must be between 0 and {$block_count}." );
}
// Map the filtered index to original index for insertion.
if ( $new_index >= $block_count ) {
$insert_pos = count( $blocks );
} else {
$insert_pos = $index_map[ $new_index ];
}
} else {
switch ( $position ) {
case 'before':
$insert_pos = $original_idx;
$new_index = $source_index;
break;
case 'after':
$insert_pos = $original_idx + 1;
$new_index = $source_index + 1;
break;
case 'start':
$insert_pos = 0;
$new_index = 0;
break;
case 'end':
default:
$insert_pos = count( $blocks );
$new_index = $block_count;
break;
}
}
array_splice( $blocks, (int) $insert_pos, 0, [ $cloned_block ] );
// @phpstan-ignore argument.type
$new_content = serialize_blocks( $blocks );
$result = wp_update_post(
[
'ID' => $post->ID,
'post_content' => $new_content,
],
true
);
if ( is_wp_error( $result ) ) {
WP_CLI::error( $result->get_error_message() );
}
if ( Utils\get_flag_value( $assoc_args, 'porcelain' ) ) {
WP_CLI::line( (string) $new_index );
} else {
WP_CLI::success( "Cloned block to index {$new_index} in post {$post->ID}." );
}
}
/**
* Extracts data from blocks.