Pam Apple
Pam Apple

Reputation: 103

require('wp-blog-header.php') does not work in a loop

I'm trying to use wp_insert_post from an external php file. This file works fine if there is no loop. It took me quite a long time but i cannot search for any similar information.

<?php

require('wp-blog-header.php');
$tmpstr = array(
          'ID' => 1,
          'post_title' => $title,
          'post_content' => $post content,
          'post_status' => 'publish',
          'post_author' => '1',
          'post_type' => $type
       );
wp_insert_post($tmpstr);
?>`

However, when i put a loop,

<?php
for ($i=0;$i<10,$i++) {
require('wp-blog-header.php');
$tmpstr = array(
          'ID' => 1,
          'post_title' => $title[$i],
          'post_content' => $post content[$i],
          'post_status' => 'publish',
          'post_author' => '1',
          'post_type' => $type
        );
   wp_insert_post($tmpstr);
}
?>

It insert only 1 time into mysql database, then it stops I have tried changing the require('wp-blog-header.php'); to require('/path/to/wp-blog-header.php'); but it still does not solve my problem. If i comment out the wp_insert_post and require('wp-blog-header.php'); and add echo $post_content[$j];echo $post_title[$j]; all values are displayed correctly in my browser

Could anyone please help me to make it loop for 10 times, so that it can insert 10 entries? Thank you in advance!

Upvotes: 0

Views: 582

Answers (2)

Cole Tobin
Cole Tobin

Reputation: 9426

you are constantly requiring the file per loop. NEVER DO THAT. put the require outside the loop. If you put it in the loop, PHP will error out saying that the function is already defined.

<?php
require('wp-blog-header.php');
for ($i = 0; $i < 10; $i++) {
$tmpstr = array(
          'ID' => 1,
          'post_title' => $title[$i],
          'post_content' => $post content[$i],
          'post_status' => 'publish',
          'post_author' => '1',
          'post_type' => $type
        );
   wp_insert_post($tmpstr);
}

Upvotes: 2

DaneSoul
DaneSoul

Reputation: 4511

for ($i=0;$i<10,$i++) {
               ^

ERROR! Must be:

for ($i=0;$i<10;$i++) {
               ^

Upvotes: 2

Related Questions