I've JUST started using WordPress..i'm trying to add posts to Wordpress using php and i came across this piece of code:

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

i understand this is the way to go when creating a post using php..my questions are:

  1. how do we execute the above php script and where do we save it in the WordPress folder?

  2. what does the 'post_category' array mean(i'd like to use a category id to add posts to WordPress)?

i'd like to mention that i've done some descent searching on the net but the resources i've found do not mention how to execute the above script.


2 Answers 2


Check the docs at http://codex.wordpress.org/Function_Reference/wp_insert_post for the parameters to use with 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 array as its argument and returns the post ID of the created post (or 0 if there is an error).

You run your function once in the context of a plugin, or worst case, in functions.php or in index.php and then remove it.

  • Why is it bad to run, etc. in functions.php all the time? I mean why it is better to run in some custom plugin with a file also something like functions.php (plugin)?
    – user385917
    Jul 30, 2017 at 9:45
  • functions.php is run on each page load by the site, so if you run code to add posts, you will end up errors or warnings that the post(s) already exist(s), or it will add the same post(s) each page load. Run as a plugin once by activating the plugin, and then deactivate the plugin and you get only one execution of the insert posts. Jul 30, 2017 at 15:31

From my own searching (also a new PHP user here!) it seems like adding and running code via the Code Snippets plugin is the easiest and safest route for these sorts of one-off code blocks.

This blog gives a good overview of how exactly to add and run PHP code with that plugin: https://www.wpbeginner.com/plugins/how-to-easily-add-custom-code-in-wordpress-without-breaking-your-site/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.