最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

posts - How to add one time a new page?

programmeradmin7浏览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');

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');
Share Improve this question edited Jul 29, 2020 at 11:17 fuxia 107k38 gold badges255 silver badges459 bronze badges asked Jul 29, 2020 at 7:21 Zed93Zed93 13 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论