Skip to content

Instantly share code, notes, and snippets.

@dwainm
Created July 24, 2014 00:29
Embed
What would you like to do?
Programatically create multiple posts for the given post type. This function runs on every page reload so be sure to run it only once
function programmatically_create_multiple_posts() {
// Initialize the page ID to -1. This indicates no action has been taken.
$post_id = -1;
$numberofposts = 40;
$new_post_type = 'portfolio';
for ($i=0; $i < $numberofposts; $i++) {
// Setup the author, slug, and title for the post
$author_id = 1;
$slug = 'example-post '. $i;
$title = $new_post_type . ' dummy '. $i;
// If the page doesn't already exist, then create it
if( null == get_page_by_title( $title ) ) {
// Set the post ID so that we know the post was created successfully
$post_id = wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => $slug,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => $new_post_type,
)
);
// Otherwise, we'll stop
} else {
// Arbitrarily use -2 to indicate that the page with the title already exists
$post_id = -2;
} // end if
}
} // end programmatically_create_post
add_filter( 'template_redirect', 'programmatically_create_multiple_posts' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment