'Create a Page on plugin activation if the post_title does not exist
I have a WordPress plugin that is creating pages on activation, but I only want it to create the pages if they don't already exist (don't want duplicates if the plugin has been re-activated).
<?
function create_pages() {
if ( ! current_user_can( 'activate_plugins' ) ) return;
$pages = array(
// Donations
array(
'post_title' => 'Donations',
'post_content' => 'Give us all your money!',
),
// Cart
array(
'post_title' => 'Cart',
'post_content' => 'Buy!',
),
);
foreach($pages as $page) {
if(get_page_by_title($page['post_title']) === null):
$new_post = array(
'post_title' => $page['post_title'],
'post_content' => $page['post_content'],
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page',
);
$post_id = wp_insert_post($new_post);
endif;
}
}
register_activation_hook(__FILE__, 'create_pages');
When I run this, no pages are created and it seems to be caused by the if(get_page_by_title($page['post_title']) === null): line. If I leave that conditional out, it creates the pages needed - but also recreates them on reactivation.
Is there anything glaring I'm missing? Any help is greatly appreciated.
Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
