Written by: John | 9th Aug 2014
WordPress Pages on the fly
Ever wanted to create WordPress pages pragmatically? Here’s how.
Recently while developing WordPress plugins I have found the need to create posts and pages for “special content”. Such as action pages or posts for external APIs.
This is done using the wp_insert_post() function (full spec here). To set up a basic post is really very simple and can be done using the following code:
$args = array( 'post_type' => 'page', //the post type. Default Post 'post_title' => 'Post Title', //The title of the post or page 'post_content' => 'This is my post.', //The content of the post or page 'post_status' => 'publish', //The status 'post_author' => 1 //The author, 1 is generally the ID of the site creator ); // Finally create the post wp_insert_post( $args );
That’s it all done! Tip: Very usefully shortcodes can be added in the post/page content at the time of creation:
'post_content' => '[my-shortcode]'