Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I wrote this little function to automatically create a post for every user of the blog but it creates an infinite loop (I disabled it to stop it creating new posts). I'm not very skilled in php, I guess the error is in the use of wp_insert_post inside the foreach, but it doesn't work simply putting it outside the braces. How can I make this function insert JUST ONE post for each author? Thanks.

$blogusers = get_users();
foreach ($blogusers as $user) {
    $my_post = array(
    'post_title'    => $user->display_name,
    'post_content'  => 'Bla bla bla.',
    'post_status'   => 'publish',
    'post_author'   => $user->ID,
    'post_type'     => 'custom'
    );

    wp_insert_post( $my_post );
}
share|improve this question
    
Where did you place this function? –  s_ha_dum Nov 14 '12 at 22:21
    
In functions.php –  She Hulk Nov 14 '12 at 22:43
add comment

1 Answer

up vote 0 down vote accepted

With that function in functions.php it is going to run on every page load and every time it runs it is going to insert a post for every user in your database. It isn't an infinite loop. You are just running it all the time.

You need to run that one time and one time only to populate your DB with posts existing users. If you have low traffic on your blog you can just paste it in, load the page, and immediately remove it. If you have much traffic you will need a different strategy.

If you want to insert a post for new users, you need to hook a similar function into the user registration system. Something like...

function create_user_post($user_id) {
    $user = get_userdata($user_id);
    $my_post = array(
    'post_title'    => $user->display_name,
    'post_content'  => 'Bla bla bla.',
    'post_status'   => 'publish',
    'post_author'   => $user->ID,
    'post_type'     => 'custom'
    );

    wp_insert_post( $my_post );
}
add_action('user_register','create_user_post');

I just made that up off the top of my head, but I think it will work. You are just complicated enough with this that it might take some implementing and then debugging. :)

For reference: get_userdata, user_register

share|improve this answer
    
This is great! It works perfectly and it's actually exactly what I wanted to do :) Thanks! –  She Hulk Nov 15 '12 at 0:28
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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