WordPress – Create post with plugin

Mar 13, 2012   //   by phpfreelancer.biz   //   Blog, Wordpress Plugin Tutorial  //  No Comments

Is it possible to create posts with a wordpress plugin by entering a title, content, category and custom field (important)?

The function for doing that is wp_insert_post.This function inserts posts (and pages) in the database. It sanitizes variables, does some checks, fills in missing variables like date/time, etc. It takes an object as its argument and returns the post ID of the created post (or 0 if there is an error).

Usage

<?php wp_insert_post( $post, $wp_error ); ?> 

Example

Before calling wp_insert_post() it is necessary to create an array to pass the necessary elements that make up a post. The wp_insert_post() will fill out a default list of these but the user is required to provide the title and content otherwise the database write will fail.

The user can provide more elements than are listed here by simply defining new keys in the database. The keys should match the names of the columns in the wp_posts table in the database.

// Create post object
  $my_post = array(
     'post_title' => 'My post',
     'post_content' => 'This is my post.',
     'post_status' => 'publish',
     'post_author' => 1,
     'post_category' => array(8,39)
  );

// Insert the post into the database
  wp_insert_post( $my_post );

Leave a comment

Share This Post

RSS Wordpress News