Creating WordPress Pages on the fly.

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]'

Related Posts

Code

Swipe close for mobile menu

Using Vanilla JS (ish) to add swipe features to mobile views.
Code

Full Width YouTube Videos

Make YouTube videos take the full width of an element while retaining the 16:9 ratio.
Code

CSS Transitions

Easy copy and paste transition css, to enable transitions to all properties.
Code

Command Line SSH stuff

Some tips and tricks for using the command line to do useful stuff, mainly just a reference for myself.
Code

Handy, dandy WordPress excerpt length function

If you have been using WordPress on multiple projects you must have come up against needing to pull a custom excerpt size? Now there are many ways to do this, eg, you could use this to pull say 80 characters…