I'm writing a WordPress plugin that I'd like to do the following:

  1. Add a WordPress plugin admin page that contains a button
  2. When you click the button, it loads an array of JSON objects from a file, then creates a WordPress post for each object

I got #1 done, and I can see the array of JSON objects loading upon button click since I use console.log. (I made the button using this tutorial - uses AJAX.)

But, how would I go about giving WordPress access to the JSON array so I can create posts using wp_insert_posts? Is this even possible?

1 Answer 1


Here I assume your json is an array of object where properties are named like wp_insert_post arguments: 'post_title', 'post_content' and so on.

function process_ajax() {  
    if ( ! isset($_POST['nonce']) || ! wp_verify_nonce($_POST['nonce'], 'mynonce') )
       die('error on checking nonce');  
    if ( ! isset($_POST['filepath']) die('no file given');
    if ( ! file_exists($_POST['filepath']) ) die('invalid file given');
    $posts = json_decode( file_get_contents($_POST['filepath']) );
    $done = 0;
    if ($posts) { 
      foreach ( $posts as $post) {
        $post = (array)$post;
        if ( isset($post['ID']) ) unset($post['ID']);
        if ( wp_insert_post($post) ) $done++;
      $str = "Successfully insert " . $done . "posts, ";
      $str .=  ( count($posts) - $done ) . ' failed.'
    } else {
      die('File contains not valid Json.');
  • But how would this work upon button click? Right now I'm using .submit() on the button in a JS file.
    – jzeta
    Commented Jul 31, 2013 at 0:55
  • See my edit and follow your tutorial for the rest.
    – gmazzap
    Commented Jul 31, 2013 at 1:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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