0

I want to insert as a custom post type some data fethced from an API, I store that data and then pass it trough a for loop, then I use the loop data to create an array to pass it to wp_insert_post function, but it does not work, not even a single post is created, the code I'm trying to run is like this:

$url = "https://api_endpoint";
$response = file_get_contents($url);
$response = json_decode($response, true);
for ($i=0; $i <sizeof($response); $i++) { 
    $my_post = array(
        'post_title'    => $response[$i]['results'],
        'post_content'  => $response[$i]['content'],
        'post_status'   => 'draft',
        'post_author'   => 1,
        'post_type'     => 'custom_pt'
    );
    $post_id = wp_insert_post( $my_post, true );
}

I doublechecked the response of the API and I'm shure the correct data is sent to the function, also I tried the function inserting just one post and works fine, so I would like to know if there is some limitation to use the function (I have not found anything at the codex) or if I'm doing something wrong.

Thanks :).

Edit: I've actually tried using a request to wp-json/wp/v2/posts, also I catch the response with

if( !is_wp_error( $post_id ) ) 

and return the response stored un $post_id (it returns nothing, the site just does nothing and I have to restart apache to re enable it).

  • Have you checked the response of wp_insert_post? I see lots of things happening but none of them are checked to see if they succeeded or not. $response might be empty, file_get_contents might fail ( have you considered using the WP HTTP API instead? ) – Tom J Nowell Mar 15 '18 at 19:37
  • I've edited the question, and I forgot to say that I've also tried with curl to fetch the API, I'm shure it works :). – J. Roberto Ramirez Matias Mar 15 '18 at 20:14
  • $response[i] should be $response[$i]. – Jacob Peattie Mar 15 '18 at 23:53
  • Lol, sorry guys, it's just a demostrative code, not the code I'm actually using, the logic of an 'wp_insert_post' calling by a loop is what I'm trying to express. And sorry for my mistakes, it actually works but when you want to do this don't do it in a custom template, use a function at functions.php or an endpoint :). – J. Roberto Ramirez Matias Mar 16 '18 at 0:30
  • 1
    you can run any code in a loop. – Joel M Mar 16 '18 at 2:45

Your Answer

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

Browse other questions tagged or ask your own question.