AnswerBun.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!

Related Questions

How to pass parameters (data) from plugin PHP to React

4  Asked on November 9, 2021 by gilbert-mizrahi

 

Get the post ID and display the images

1  Asked on November 9, 2021

   

Admin user column sort by numeric meta key

0  Asked on November 9, 2021 by david-sticker

     

Admin role not really admin

1  Asked on November 6, 2021 by adrian-le-roy-devezin

   

Jquery Validation Engine with Conatct Form 7

1  Asked on November 6, 2021 by magecode

 

How many post WordPress can handle?

1  Asked on November 6, 2021 by kabir

   

Bad request 400 from custom ajax call

3  Asked on November 6, 2021 by jpl

   

How to add custom preview urls for some pages?

0  Asked on November 6, 2021 by haxpanel

   

Password protect directory but not files

1  Asked on October 30, 2021

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir