0

I m working on a plugin and i would add a page for every value of my database.

But for every refresh, a new page with same name will be added. How can i fix this?

for ($i = 0; $i < count($namepages); $i++) {
       mic_create_new_page($name[$i],$namepages[$i]);    
}

function mic_create_new_page($name, $namepages) {
    global $user_ID;
    if (post_exists($namepages) == false) {
        $new_post = array(
            'post_title' => 'Services ' . $name,
            'post_content' => 'New post content',
            'post_status' => 'publish',
            'post_date' => date('Y-m-d H:i:s'),
            'post_author' => $user_ID,
            'post_type' => 'page',
            'post_name' => $namepages
        );
        $post_id = wp_insert_post($new_post);
    }
}
    
register_activation_hook(__FILE__, 'create_new_page');
0

If this code is in functions.php or directly in plugin code, the for loop at the top will run every time Wordpress is loaded, and the hook at the end refers to a function which doesn't exist.

So probably what you want is to put the top code in a function:

function zed93_create_new_page {
    for ($i = 0; $i < count($namepages); $i++) {
        mic_create_new_page($name[$i],$namepages[$i]);    
    }
}

And correct your hook to:

register_activation_hook(__FILE__, 'zed93_create_new_page');

Note the function name can be anything, but making it unique to your project helps avoid collisions with other plugins / themes.

  • I get some values from DB, how can i refresh the function for every values addes in my db? PS Thank you ! – Zed93 Jul 29 '20 at 9:44
  • Hi @Zed93, you're welcome. That sounds like it could be a separate question? You want to update some of the values at some other time? – mozboz Jul 29 '20 at 9:46
  • Yes. I have a list of city. I would like add a new page every time a new city is added in my table of DB. – Zed93 Jul 29 '20 at 9:48
  • That sounds like probably a whole new question so best to post it as a new question. – mozboz Jul 29 '20 at 9:50
  • OK i will do in a few minutes ! thank you – Zed93 Jul 29 '20 at 9:51

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.