Skip to content

Instantly share code, notes, and snippets.

@Oceas
Last active September 16, 2019 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oceas/fc9b863cce38c8d40fc863b50967fc8b to your computer and use it in GitHub Desktop.
Save Oceas/fc9b863cce38c8d40fc863b50967fc8b to your computer and use it in GitHub Desktop.
WDS WP-CLI 101 Putting It Together
/**
* Generate posts with meta values.
*
* @param Array $args Arguments in array format.
* @param Array $assoc_args Key value arguments stored in associated array format.
* @since 1.0.0
* @author Scott Anderson
*/
public function generate_posts( $args, $assoc_args ) {
// Get Post Details.
$desired_posts_to_generate = (int) $args[0]; // First argument is how many posts should be generated.
$title_prepend = $args[1]; // Second argument should be the title of posts generated. This will be used with index in loop to generate a title.
$author_id = (int) $args[2]; // Id of author who to assign generated post to.
$progress = \WP_CLI\Utils\make_progress_bar( 'Generating Posts', $desired_posts_to_generate );
for ( $i = 0; $i < $desired_posts_to_generate; $i++ ) {
// Code used to generate a post.
$my_post = array(
'post_title' => $title_prepend . ' ' . ($i + 1),
'post_status' => 'publish',
'post_author' => $author_id,
'post_type' => 'post',
'tags_input' => [ 'generated' ],
'meta_input' => $assoc_args, // Simply passes all key value pairs to posts generated that can be used in testing.
);
// Insert the post into the database.
wp_insert_post( $my_post );
$progress->tick();
}
$progress->finish();
WP_CLI::success( $desired_posts_to_generate. ' posts generated!' ); // Prepends Success to message
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment