Programmatically Adding Posts WordPress

December 5, 2010

I spent a long time to find code that looks like something like this. In vain I have spent time and decide to make my blog where I can write whatever is bothering me and I successfully solved.

Here is an example of a function that is used for publishing articles in PHP. Up to you to get the best possible way…

function addPost()
$new_post = array(
'post_title' => $post_title,
'post_content' => $post_content,
'post_status' => $post_status,
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $post_author,
'post_type' => $post_type,
'post_category' => array(0)
//adding post
$post_id = wp_insert_post($new_post);
//adding tags, adding category
$tags = tagsToArray('tag1,t ag2,tag 3, t a g 3');
$cat = categoryToArray('cat 1, cat2,c at2,c a t 3');
wp_set_object_terms( $post_id, $tags, 'post_tag');
wp_set_object_terms( $post_id, $cat, 'category');


I use my function for converting string to array of tags(strings) and category

function tagsToArray($s)
$tags = explode(",",$s);
$tagsReturn = array(0);
for ($j=0;$j!=count($tags); $j++)
return $tagsReturn;
function categoryToArray($s)
$category = explode(",",$s);
$categoryReturn = array(0);
for ($j=0;$j!=count($category); $j++)
return $categoryReturn;

$new_post = array(
‘post_title’ => Hello, World! This is post maked programmatically. I am post title,
‘post_content’ => Hello, World! This is post maked programmatically. I am post content.,
‘post_status’ => ‘publish’,
‘post_date’ => date(‘Y-m-d H:i:s’),
‘post_author’ => 0,// I know that I am with that id
‘post_type’ => ‘post’,
‘post_category’ => array(0)

$post_id = wp_insert_post($new_post);
$tags = tagsToArray(‘examples,php,programmatically’);
$cat = categoryToArray(‘examples’);
wp_set_object_terms( $post_id, $tags, ‘post_tag’);
wp_set_object_terms( $post_id, $cat, ‘category’);