TransWikia.com

How to add one time a new page?

WordPress Development Asked by Zed93 on October 17, 2020

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');

One Answer

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.

Correct answer by mozboz on October 17, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP