Add WordPress post type content programatically

To load dummy content programatically load the content below into your functions.php.

This function runs on every page reload so be sure to run it only once and then remove it. Firstly setup the number of posts you need and then also specify the post type. After doing this proceed to your website front end  and reload the page.

After this your dummy posts should be added. Remove that code from your functions..php file and check your admin dashboard.


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' );

view raw

functions.php

hosted with ❤ by GitHub

This is a modified version of Tom McFarlin’s post ( http://tommcfarlin.com/programmatically-create-a-post-in-wordpress/ )

2 thoughts on “Add WordPress post type content programatically

  1. Why does it still duplicating my posts even though It is already posted. Seems like the conditional statement get_page_by_title returns true ?

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s