Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.