-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathPost_Command.php
More file actions
1244 lines (1143 loc) · 35.9 KB
/
Post_Command.php
File metadata and controls
1244 lines (1143 loc) · 35.9 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 WP_CLI\CommandWithDBObject;
use WP_CLI\Entity\Block_Processor_Helper;
use WP_CLI\Fetchers\Post as PostFetcher;
use WP_CLI\Fetchers\User as UserFetcher;
use WP_CLI\Utils;
/**
* Manages posts, content, and meta.
*
* ## EXAMPLES
*
* # Create a new post.
* $ wp post create --post_type=post --post_title='A sample post'
* Success: Created post 123.
*
* # Update an existing post.
* $ wp post update 123 --post_status=draft
* Success: Updated post 123.
*
* # Delete an existing post.
* $ wp post delete 123
* Success: Trashed post 123.
*
* @package wp-cli
*/
class Post_Command extends CommandWithDBObject {
protected $obj_type = 'post';
protected $obj_fields = [
'ID',
'post_title',
'post_name',
'post_date',
'post_status',
];
private $fetcher;
public function __construct() {
$this->fetcher = new PostFetcher();
}
/**
* Creates a new post.
*
* ## OPTIONS
*
* [--post_author=<post_author>]
* : The ID of the user who added the post. Default is the current user ID.
*
* [--post_date=<post_date>]
* : The date of the post. Default is the current time.
*
* [--post_date_gmt=<post_date_gmt>]
* : The date of the post in the GMT timezone. Default is the value of $post_date.
*
* [--post_content=<post_content>]
* : The post content. Default empty.
*
* [--post_content_filtered=<post_content_filtered>]
* : The filtered post content. Default empty.
*
* [--post_title=<post_title>]
* : The post title. Default empty.
*
* [--post_excerpt=<post_excerpt>]
* : The post excerpt. Default empty.
*
* [--post_status=<post_status>]
* : The post status. Default 'draft'.
*
* [--post_type=<post_type>]
* : The post type. Default 'post'.
*
* [--comment_status=<comment_status>]
* : Whether the post can accept comments. Accepts 'open' or 'closed'. Default is the value of 'default_comment_status' option.
*
* [--ping_status=<ping_status>]
* : Whether the post can accept pings. Accepts 'open' or 'closed'. Default is the value of 'default_ping_status' option.
*
* [--post_password=<post_password>]
* : The password to access the post. Default empty.
*
* [--post_name=<post_name>]
* : The post name. Default is the sanitized post title when creating a new post.
*
* [--from-post=<post_id>]
* : Post id of a post to be duplicated.
*
* [--to_ping=<to_ping>]
* : Space or carriage return-separated list of URLs to ping. Default empty.
*
* [--pinged=<pinged>]
* : Space or carriage return-separated list of URLs that have been pinged. Default empty.
*
* [--post_modified=<post_modified>]
* : The date when the post was last modified. Default is the current time.
*
* [--post_modified_gmt=<post_modified_gmt>]
* : The date when the post was last modified in the GMT timezone. Default is the current time.
*
* [--post_parent=<post_parent>]
* : Set this for the post it belongs to, if any. Default 0.
*
* [--menu_order=<menu_order>]
* : The order the post should be displayed in. Default 0.
*
* [--post_mime_type=<post_mime_type>]
* : The mime type of the post. Default empty.
*
* [--guid=<guid>]
* : Global Unique ID for referencing the post. Default empty.
*
* [--post_category=<post_category>]
* : Array of category names, slugs, or IDs. Defaults to value of the 'default_category' option.
*
* [--tags_input=<tags_input>]
* : Array of tag names, slugs, or IDs. Default empty.
*
* [--tax_input=<tax_input>]
* : Array of taxonomy terms keyed by their taxonomy name. Default empty.
*
* Note: In WordPress core, this normally requires a user context to satisfy capability checks. WP-CLI bypasses this for convenience. See https://core.trac.wordpress.org/ticket/19373
*
* [--meta_input=<meta_input>]
* : Array in JSON format of post meta values keyed by their post meta key. Default empty.
*
* [<file>]
* : Read post content from <file>. If this value is present, the
* `--post_content` argument will be ignored.
*
* Passing `-` as the filename will cause post content to
* be read from STDIN.
*
* [--<field>=<value>]
* : Associative args for the new post. See wp_insert_post().
*
* [--edit]
* : Immediately open system's editor to write or edit post content.
*
* If content is read from a file, from STDIN, or from the `--post_content`
* argument, that text will be loaded into the editor.
*
* [--porcelain]
* : Output just the new post id.
*
*
* ## EXAMPLES
*
* # Create post and schedule for future
* $ wp post create --post_type=post --post_title='A future post' --post_status=future --post_date='2030-12-01 07:00:00'
* Success: Created post 1921.
*
* # Create post with content from given file
* $ wp post create ./post-content.txt --post_category=201,345 --post_title='Post from file'
* Success: Created post 1922.
*
* # Create a post with multiple meta values.
* $ wp post create --post_title='A post' --post_content='Just a small post.' --meta_input='{"key1":"value1","key2":"value2"}'
* Success: Created post 1923.
*
* # Create a duplicate post from existing posts.
* $ wp post create --from-post=123 --post_title='Different Title'
* Success: Created post 2350.
*/
public function create( $args, $assoc_args ) {
if ( ! empty( $args[0] ) ) {
$assoc_args['post_content'] = $this->read_from_file_or_stdin( $args[0] );
}
if ( Utils\get_flag_value( $assoc_args, 'edit' ) ) {
$input = Utils\get_flag_value( $assoc_args, 'post_content', '' );
$output = $this->_edit( $input, 'WP-CLI: New Post' );
if ( $output ) {
$assoc_args['post_content'] = $output;
} else {
$assoc_args['post_content'] = $input;
}
}
if ( isset( $assoc_args['post_category'] ) ) {
$assoc_args['post_category'] = $this->get_category_ids( $assoc_args['post_category'] );
}
$array_arguments = [ 'meta_input', 'tax_input' ];
$assoc_args = Utils\parse_shell_arrays( $assoc_args, $array_arguments );
if ( isset( $assoc_args['from-post'] ) ) {
$post = $this->fetcher->get_check( $assoc_args['from-post'] );
$post_arr = get_object_vars( $post );
$post_id = $post_arr['ID'];
unset( $post_arr['post_date'] );
unset( $post_arr['post_date_gmt'] );
unset( $post_arr['guid'] );
unset( $post_arr['ID'] );
if ( empty( $assoc_args['meta_input'] ) ) {
$assoc_args['meta_input'] = $this->get_metadata( $post_id );
}
if ( empty( $assoc_args['post_category'] ) ) {
$post_arr['post_category'] = $this->get_category( $post_id );
}
if ( empty( $assoc_args['tags_input'] ) ) {
$post_arr['tags_input'] = $this->get_tags( $post_id );
}
$assoc_args = array_merge( $post_arr, $assoc_args );
}
$assoc_args = wp_slash( $assoc_args );
parent::_create(
$args,
$assoc_args,
function ( $params ) {
$filter_callback = null;
if ( 0 === get_current_user_id() && ! empty( $params['tax_input'] ) ) {
$allowed_caps = [];
/**
* @var string $taxonomy
*/
foreach ( array_keys( $params['tax_input'] ) as $taxonomy ) {
$tax_obj = get_taxonomy( $taxonomy );
if ( $tax_obj ) {
$primitive_caps = map_meta_cap( $tax_obj->cap->assign_terms, 0 );
$allowed_caps = array_merge( $allowed_caps, $primitive_caps );
}
}
if ( ! empty( $allowed_caps ) ) {
$filter_callback = function ( $allcaps, $caps ) use ( $allowed_caps ) {
foreach ( $caps as $cap ) {
if ( in_array( $cap, $allowed_caps, true ) ) {
$allcaps[ $cap ] = true;
}
}
return $allcaps;
};
add_filter( 'user_has_cap', $filter_callback, 10, 2 );
}
}
$result = wp_insert_post( $params, true );
if ( $filter_callback ) {
remove_filter( 'user_has_cap', $filter_callback );
}
return $result;
}
);
}
/**
* Updates one or more existing posts.
*
* ## OPTIONS
*
* <id>...
* : One or more IDs of posts to update.
*
* [--post_author=<post_author>]
* : The ID of the user who added the post. Default is the current user ID.
*
* [--post_date=<post_date>]
* : The date of the post. Default is the current time.
*
* [--post_date_gmt=<post_date_gmt>]
* : The date of the post in the GMT timezone. Default is the value of $post_date.
*
* [--post_content=<post_content>]
* : The post content. Default empty.
*
* [--post_content_filtered=<post_content_filtered>]
* : The filtered post content. Default empty.
*
* [--post_title=<post_title>]
* : The post title. Default empty.
*
* [--post_excerpt=<post_excerpt>]
* : The post excerpt. Default empty.
*
* [--post_status=<post_status>]
* : The post status. Default 'draft'.
*
* [--post_type=<post_type>]
* : The post type. Default 'post'.
*
* [--comment_status=<comment_status>]
* : Whether the post can accept comments. Accepts 'open' or 'closed'. Default is the value of 'default_comment_status' option.
*
* [--ping_status=<ping_status>]
* : Whether the post can accept pings. Accepts 'open' or 'closed'. Default is the value of 'default_ping_status' option.
*
* [--post_password=<post_password>]
* : The password to access the post. Default empty.
*
* [--post_name=<post_name>]
* : The post name. Default is the sanitized post title when creating a new post.
*
* [--to_ping=<to_ping>]
* : Space or carriage return-separated list of URLs to ping. Default empty.
*
* [--pinged=<pinged>]
* : Space or carriage return-separated list of URLs that have been pinged. Default empty.
*
* [--post_modified=<post_modified>]
* : The date when the post was last modified. Default is the current time.
*
* [--post_modified_gmt=<post_modified_gmt>]
* : The date when the post was last modified in the GMT timezone. Default is the current time.
*
* [--post_parent=<post_parent>]
* : Set this for the post it belongs to, if any. Default 0.
*
* [--menu_order=<menu_order>]
* : The order the post should be displayed in. Default 0.
*
* [--post_mime_type=<post_mime_type>]
* : The mime type of the post. Default empty.
*
* [--guid=<guid>]
* : Global Unique ID for referencing the post. Default empty.
*
* [--post_category=<post_category>]
* : Array of category names, slugs, or IDs. Defaults to value of the 'default_category' option.
*
* [--tags_input=<tags_input>]
* : Array of tag names, slugs, or IDs. Default empty.
*
* [--tax_input=<tax_input>]
* : Array of taxonomy terms keyed by their taxonomy name. Default empty.
*
* Note: In WordPress core, this normally requires a user context to satisfy capability checks. WP-CLI bypasses this for convenience. See https://core.trac.wordpress.org/ticket/19373
*
* [--meta_input=<meta_input>]
* : Array in JSON format of post meta values keyed by their post meta key. Default empty.
*
* [<file>]
* : Read post content from <file>. If this value is present, the
* `--post_content` argument will be ignored.
*
* Passing `-` as the filename will cause post content to
* be read from STDIN.
*
* --<field>=<value>
* : One or more fields to update. See wp_insert_post().
*
* [--defer-term-counting]
* : Recalculate term count in batch, for a performance boost.
*
* ## EXAMPLES
*
* $ wp post update 123 --post_name=something --post_status=draft
* Success: Updated post 123.
*
* # Update a post with multiple meta values.
* $ wp post update 123 --meta_input='{"key1":"value1","key2":"value2"}'
* Success: Updated post 123.
*
* # Update multiple posts at once.
* $ wp post update 123 456 --post_author=789
* Success: Updated post 123.
* Success: Updated post 456.
*
* # Update all posts of a given post type at once.
* $ wp post update $(wp post list --post_type=page --format=ids) --post_author=123
* Success: Updated post 123.
* Success: Updated post 456.
*/
public function update( $args, $assoc_args ) {
foreach ( $args as $key => $arg ) {
if ( is_numeric( $arg ) ) {
continue;
}
$assoc_args['post_content'] = $this->read_from_file_or_stdin( $arg );
unset( $args[ $key ] );
break;
}
if ( isset( $assoc_args['post_category'] ) ) {
$assoc_args['post_category'] = $this->get_category_ids( $assoc_args['post_category'] );
}
$array_arguments = [ 'meta_input', 'tax_input' ];
$assoc_args = Utils\parse_shell_arrays( $assoc_args, $array_arguments );
$assoc_args = wp_slash( $assoc_args );
parent::_update(
$args,
$assoc_args,
function ( $params ) {
$filter_callback = null;
if ( 0 === get_current_user_id() && ! empty( $params['tax_input'] ) ) {
$allowed_caps = [];
/**
* @var string $taxonomy
*/
foreach ( array_keys( $params['tax_input'] ) as $taxonomy ) {
$tax_obj = get_taxonomy( $taxonomy );
if ( $tax_obj ) {
$primitive_caps = map_meta_cap( $tax_obj->cap->assign_terms, 0 );
$allowed_caps = array_merge( $allowed_caps, $primitive_caps );
}
}
if ( ! empty( $allowed_caps ) ) {
$filter_callback = function ( $allcaps, $caps ) use ( $allowed_caps ) {
foreach ( $caps as $cap ) {
if ( in_array( $cap, $allowed_caps, true ) ) {
$allcaps[ $cap ] = true;
}
}
return $allcaps;
};
add_filter( 'user_has_cap', $filter_callback, 10, 2 );
}
}
$result = wp_update_post( $params, true );
if ( $filter_callback ) {
remove_filter( 'user_has_cap', $filter_callback );
}
return $result;
}
);
}
/**
* Launches system editor to edit post content.
*
* ## OPTIONS
*
* <id>
* : The ID of the post to edit.
*
* ## EXAMPLES
*
* # Launch system editor to edit post
* $ wp post edit 123
*/
public function edit( $args, $assoc_args ) {
$post = $this->fetcher->get_check( $args[0] );
$result = $this->_edit( $post->post_content, "WP-CLI post {$post->ID}" );
if ( false === $result ) {
WP_CLI::warning( 'No change made to post content.' );
} else {
$this->update( $args, [ 'post_content' => $result ] );
}
}
// phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore -- Whitelisting to provide backward compatibility to classes possibly extending this class.
protected function _edit( $content, $title ) {
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
$content = apply_filters( 'the_editor_content', $content );
$output = Utils\launch_editor_for_input( $content, $title );
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
return ( is_string( $output ) ) ? apply_filters( 'content_save_pre', $output ) : $output;
}
/**
* Gets details about a post.
*
* ## OPTIONS
*
* <id>
* : The ID of the post to get.
*
* [--field=<field>]
* : Instead of returning the whole post, returns the value of a single field.
*
* [--fields=<fields>]
* : Limit the output to specific fields. Defaults to all fields.
*
* [--format=<format>]
* : Render output in a particular format.
* ---
* default: table
* options:
* - table
* - csv
* - json
* - yaml
* ---
*
* ## EXAMPLES
*
* # Save the post content to a file
* $ wp post get 123 --field=content > file.txt
*
* # Get the block version of a post (1 = has blocks, 0 = no blocks)
* # Requires WordPress 5.0+.
* $ wp post get 123 --field=block_version
* 1
*/
public function get( $args, $assoc_args ) {
$post = $this->fetcher->get_check( $args[0] );
$post_arr = get_object_vars( $post );
unset( $post_arr['filter'] );
if ( ! isset( $post_arr['url'] ) ) {
$post_arr['url'] = get_permalink( $post->ID );
}
if ( function_exists( 'block_version' ) ) {
$post_arr['block_version'] = block_version( $post->post_content );
}
if ( empty( $assoc_args['fields'] ) ) {
$assoc_args['fields'] = array_keys( $post_arr );
}
$formatter = $this->get_formatter( $assoc_args );
$formatter->display_item( $post_arr );
}
/**
* Deletes an existing post.
*
* ## OPTIONS
*
* <id>...
* : One or more IDs of posts to delete.
*
* [--force]
* : Skip the trash bin.
*
* [--defer-term-counting]
* : Recalculate term count in batch, for a performance boost.
*
* ## EXAMPLES
*
* # Delete post skipping trash
* $ wp post delete 123 --force
* Success: Deleted post 123.
*
* # Delete multiple posts
* $ wp post delete 123 456 789
* Success: Trashed post 123.
* Success: Trashed post 456.
* Success: Trashed post 789.
*
* # Delete all pages
* $ wp post delete $(wp post list --post_type='page' --format=ids)
* Success: Trashed post 1164.
* Success: Trashed post 1186.
*
* # Delete all posts in the trash
* $ wp post delete $(wp post list --post_status=trash --format=ids)
* Success: Deleted post 1268.
* Success: Deleted post 1294.
*/
public function delete( $args, $assoc_args ) {
$defaults = [ 'force' => false ];
$assoc_args = array_merge( $defaults, $assoc_args );
parent::_delete( $args, $assoc_args, [ $this, 'delete_callback' ] );
}
/**
* Callback used to delete a post.
*
* @param $post_id
* @param $assoc_args
* @return array
*/
protected function delete_callback( $post_id, $assoc_args ) {
$status = get_post_status( $post_id );
$post_type = get_post_type( $post_id );
$force_delete = $assoc_args['force'] || 'trash' === $status || 'revision' === $post_type;
if ( $force_delete || ! EMPTY_TRASH_DAYS ) {
if ( ! wp_delete_post( $post_id, true ) ) {
return [ 'error', "Failed deleting post {$post_id}." ];
}
return [ 'success', "Deleted post {$post_id}." ];
}
// Use wp_trash_post() directly because wp_delete_post() only auto-trashes
// 'post' and 'page' types, permanently deleting all other post types even
// when $force_delete is false. wp_trash_post() works for all post types.
if ( wp_trash_post( $post_id ) ) {
return [ 'success', "Trashed post {$post_id}." ];
}
return [ 'error', "Failed trashing post {$post_id}." ];
}
/**
* Gets a list of posts.
*
* Display posts based on all arguments supported by [WP_Query()](https://developer.wordpress.org/reference/classes/wp_query/).
* Only shows post types marked as post by default.
*
* ## OPTIONS
*
* [--<field>=<value>]
* : One or more args to pass to WP_Query.
*
* [--field=<field>]
* : Prints the value of a single field for each post.
*
* [--fields=<fields>]
* : Limit the output to specific object fields.
*
* [--format=<format>]
* : Render output in a particular format.
* ---
* default: table
* options:
* - table
* - csv
* - ids
* - json
* - count
* - yaml
* ---
*
* ## AVAILABLE FIELDS
*
* These fields will be displayed by default for each post:
*
* * ID
* * post_title
* * post_name
* * post_date
* * post_status
*
* These fields are optionally available:
*
* * post_author
* * post_date_gmt
* * post_content
* * post_excerpt
* * comment_status
* * ping_status
* * post_password
* * to_ping
* * pinged
* * post_modified
* * post_modified_gmt
* * post_content_filtered
* * post_parent
* * guid
* * menu_order
* * post_type
* * post_mime_type
* * comment_count
* * filter
* * url
*
* ## EXAMPLES
*
* # List post
* $ wp post list --field=ID
* 568
* 829
* 1329
* 1695
*
* # List posts in JSON
* $ wp post list --post_type=post --posts_per_page=5 --format=json
* [{"ID":1,"post_title":"Hello world!","post_name":"hello-world","post_date":"2015-06-20 09:00:10","post_status":"publish"},{"ID":1178,"post_title":"Markup: HTML Tags and Formatting","post_name":"markup-html-tags-and-formatting","post_date":"2013-01-11 20:22:19","post_status":"draft"}]
*
* # List all pages
* $ wp post list --post_type=page --fields=post_title,post_status
* +-------------+-------------+
* | post_title | post_status |
* +-------------+-------------+
* | Sample Page | publish |
* +-------------+-------------+
*
* # List ids of all pages and posts
* $ wp post list --post_type=page,post --format=ids
* 15 25 34 37 198
*
* # List given posts
* $ wp post list --post__in=1,3
* +----+--------------+-------------+---------------------+-------------+
* | ID | post_title | post_name | post_date | post_status |
* +----+--------------+-------------+---------------------+-------------+
* | 3 | Lorem Ipsum | lorem-ipsum | 2016-06-01 14:34:36 | publish |
* | 1 | Hello world! | hello-world | 2016-06-01 14:31:12 | publish |
* +----+--------------+-------------+---------------------+-------------+
*
* # List given post by a specific author
* $ wp post list --author=2
* +----+-------------------+-------------------+---------------------+-------------+
* | ID | post_title | post_name | post_date | post_status |
* +----+-------------------+-------------------+---------------------+-------------+
* | 14 | New documentation | new-documentation | 2021-06-18 21:05:11 | publish |
* +----+-------------------+-------------------+---------------------+-------------+
*
* @subcommand list
*/
public function list_( $args, $assoc_args ) {
$formatter = $this->get_formatter( $assoc_args );
$defaults = [
'posts_per_page' => -1,
'post_status' => 'any',
];
$array_arguments = [ 'date_query', 'tax_query', 'meta_query' ];
$assoc_args = Utils\parse_shell_arrays( $assoc_args, $array_arguments );
$query_args = array_merge( $defaults, $assoc_args );
$query_args = self::process_csv_arguments_to_arrays( $query_args );
if ( isset( $query_args['post_type'] ) && 'any' !== $query_args['post_type'] ) {
$query_args['post_type'] = explode( ',', $query_args['post_type'] );
}
if ( 'ids' === $formatter->format ) {
$query_args['fields'] = 'ids';
$query = new WP_Query( $query_args );
// @phpstan-ignore argument.type
echo implode( ' ', $query->posts );
} elseif ( 'count' === $formatter->format ) {
$query_args['fields'] = 'ids';
$query = new WP_Query( $query_args );
$formatter->display_items( $query->posts );
} else {
$query = new WP_Query( $query_args );
$posts = array_map(
function ( $post ) {
/**
* @var \WP_Post $post
*/
// @phpstan-ignore property.notFound
$post->url = get_permalink( $post->ID );
return $post;
},
$query->posts
);
$formatter->display_items( $posts );
}
}
/**
* Generates some posts.
*
* Creates a specified number of new posts with dummy data.
*
* ## OPTIONS
*
* [--count=<number>]
* : How many posts to generate?
* ---
* default: 100
* ---
*
* [--post_type=<type>]
* : The type of the generated posts.
* ---
* default: post
* ---
*
* [--post_status=<status>]
* : The status of the generated posts.
* ---
* default: publish
* ---
*
* [--post_title=<post_title>]
* : The post title.
* ---
* default:
* ---
*
* [--post_author=<login>]
* : The author of the generated posts.
* ---
* default:
* ---
*
* [--post_date=<yyyy-mm-dd-hh-ii-ss>]
* : The date of the post. Default is the current time.
*
* [--post_date_gmt=<yyyy-mm-dd-hh-ii-ss>]
* : The date of the post in the GMT timezone. Default is the value of --post_date.
*
* [--post_content]
* : If set, the command reads the post_content from STDIN.
*
* [--max_depth=<number>]
* : For hierarchical post types, generate child posts down to a certain depth.
* ---
* default: 1
* ---
*
* [--format=<format>]
* : Render output in a particular format.
* ---
* default: progress
* options:
* - progress
* - ids
* ---
*
* ## EXAMPLES
*
* # Generate posts.
* $ wp post generate --count=10 --post_type=page --post_date=1999-01-04
* Generating posts 100% [================================================] 0:01 / 0:04
*
* # Generate posts with fetched content.
* $ curl -N https://loripsum.net/api/5 | wp post generate --post_content --count=10
* % Total % Received % Xferd Average Speed Time Time Time Current
* Dload Upload Total Spent Left Speed
* 100 2509 100 2509 0 0 616 0 0:00:04 0:00:04 --:--:-- 616
* Generating posts 100% [================================================] 0:01 / 0:04
*
* # Add meta to every generated posts.
* $ wp post generate --format=ids | xargs -d ' ' -I % wp post meta add % foo bar
* Success: Added custom field.
* Success: Added custom field.
* Success: Added custom field.
*
* @param array<string> $args Positional arguments. Unused.
* @param array{count: string, post_type: string, post_status: string, post_title: string, post_author: string, post_date?: string, post_date_gmt?: string, post_content?: string, max_depth: string, format: string} $assoc_args Associative arguments.
*/
public function generate( $args, $assoc_args ) {
global $wpdb;
$defaults = [
'count' => 100,
'max_depth' => 1,
'post_type' => 'post',
'post_status' => 'publish',
'post_author' => false,
'post_date' => '',
'post_date_gmt' => '',
'post_content' => '',
'post_title' => '',
];
$post_data = array_merge( $defaults, $assoc_args );
$post_data['post_date'] = $this->maybe_convert_hyphenated_date_format( $post_data['post_date'] );
$post_data['post_date_gmt'] = $this->maybe_convert_hyphenated_date_format( $post_data['post_date_gmt'] );
// Add time if the string is a valid date without time.
$date = DateTime::createFromFormat( 'Y-m-d', $post_data['post_date'] );
if ( $date && $date->format( 'Y-m-d' ) === $post_data['post_date'] ) {
$post_data['post_date'] .= ' 00:00:00';
}
$date_gmt = DateTime::createFromFormat( 'Y-m-d', $post_data['post_date_gmt'] );
if ( $date_gmt && $date_gmt->format( 'Y-m-d' ) === $post_data['post_date_gmt'] ) {
$post_data['post_date_gmt'] .= ' 00:00:00';
}
// In older WordPress versions, wp_insert_post post dates default to the current time when a value is absent. We need to send a value for post_date_gmt if post_date is set and vice versa.
if ( ! empty( $post_data['post_date'] ) && empty( $post_data['post_date_gmt'] ) ) {
$post_data['post_date_gmt'] = get_gmt_from_date( $post_data['post_date'] );
}
if ( ! empty( $post_data['post_date_gmt'] ) && empty( $post_data['post_date'] ) ) {
$post_data['post_date'] = get_date_from_gmt( $post_data['post_date_gmt'] );
}
if ( ! post_type_exists( $post_data['post_type'] ) ) {
WP_CLI::error( "'{$post_data['post_type']}' is not a registered post type." );
}
if ( $post_data['post_author'] ) {
$user_fetcher = new UserFetcher();
$post_data['post_author'] = $user_fetcher->get_check( $post_data['post_author'] )->ID;
}
if ( Utils\get_flag_value( $assoc_args, 'post_content' ) ) {
if ( ! Utils\has_stdin() ) {
WP_CLI::error( 'The parameter `post_content` reads from STDIN.' );
}
$post_data['post_content'] = (string) file_get_contents( 'php://stdin' );
}
// Get the total number of posts.
$total = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = %s", $post_data['post_type'] ) );
/**
* @var \WP_Post_Type $post_type
*/
$post_type = get_post_type_object( $post_data['post_type'] );
$label = ! empty( $post_data['post_title'] )
? $post_data['post_title']
: $post_type->labels->singular_name;
$limit = $post_data['count'] + $total;
$format = Utils\get_flag_value( $assoc_args, 'format', 'progress' );
$notify = false;
if ( 'progress' === $format ) {
$notify = Utils\make_progress_bar( 'Generating posts', (int) $post_data['count'] );
}
$previous_post_id = 0;
$current_depth = 1;
$current_parent = 0;
for ( $index = $total; $index < $limit; $index++ ) {
if ( $post_type->hierarchical ) {
if ( $this->maybe_make_child() && $current_depth < $post_data['max_depth'] ) {
$current_parent = $previous_post_id;
++$current_depth;
} elseif ( $this->maybe_reset_depth() ) {
$current_depth = 1;
$current_parent = 0;
}
}
$args = [
'post_type' => $post_data['post_type'],
'post_title' => ( ! empty( $post_data['post_title'] ) && $index === $total )
? $label
: "{$label} {$index}",
'post_status' => $post_data['post_status'],
'post_author' => (int) $post_data['post_author'],
'post_parent' => $current_parent,
'post_name' => ! empty( $post_data['post_title'] )
? sanitize_title( $post_data['post_title'] . ( $index === $total ? '' : "-{$index}" ) )
: "post-{$index}",
'post_date' => $post_data['post_date'],
'post_date_gmt' => $post_data['post_date_gmt'],
'post_content' => $post_data['post_content'],
];
$post_id = wp_insert_post( $args, true );
if ( is_wp_error( $post_id ) ) {
WP_CLI::warning( $post_id );
} else {
$previous_post_id = $post_id;
if ( 'ids' === $format ) {
echo $post_id;
if ( $index < $limit - 1 ) {
echo ' ';
}
}
}
if ( 'progress' === $format ) {
// @phpstan-ignore method.nonObject
$notify->tick();
}
}
if ( 'progress' === $format ) {
// @phpstan-ignore method.nonObject
$notify->finish();
}
}
/**
* Gets the post ID for a given URL.
*
* ## OPTIONS
*
* <url>
* : The URL of the post to get.
*
* ## EXAMPLES
*
* # Get post ID by URL
* $ wp post url-to-id https://example.com/?p=1
* 1
*
* @subcommand url-to-id
*/
public function url_to_id( $args, $assoc_args ) {
$post_id = url_to_postid( $args[0] );
$post = get_post( $post_id );
if ( null === $post ) {
WP_CLI::error( "Could not get post with url $args[0]." );
}
WP_CLI::print_value( $post_id, $assoc_args );
}
private function maybe_make_child() {